Basic Input/Output

Input/Output (I/O) operations are fundamental to any programming language, allowing programs to interact with users and external devices. In C++, I/O operations are performed using the standard input/output streams: cin for input and cout for output.

Standard Output (cout)

The cout object is used to output data to the standard output stream (usually the console). It is part of the iostream library.

				
					#include <iostream>

int main() {
    std::cout << "Hello, world!" << std::endl;
    return 0;
}

				
			
				
					// output //
Hello, world!

				
			

Explanation:

  • std::cout is used to print data to the console.
  • << is the stream insertion operator, which inserts data into the output stream.
  • "Hello, world!" is the data being printed.
  • std::endl is used to insert a newline character and flush the output buffer.

Standard Input (cin)

The cin object is used to read data from the standard input stream (usually user input from the keyboard). It is also part of the iostream library.

				
					#include <iostream>

int main() {
    int age;
    std::cout << "Enter your age: ";
    std::cin >> age;
    std::cout << "Your age is: " << age << std::endl;
    
    int num;
    std::string str;
    std::cout << "Enter an integer and a string: ";
    std::cin >> num >> str;
    std::cout << "Integer: " << num << std::endl;
    std::cout << "String: " << str << std::endl;
    
    return 0;
}

				
			
				
					// output //
Enter your age: 15
Your age is: 15
Enter an integer and a string: 42 Hello
Integer: 42
String: Hello


				
			

Explanation:

  • std::cin is used to read data from the console.
  • >> is the stream extraction operator, which extracts data from the input stream.
  • age is a variable to store the user’s input.

Formatted Output

You can format output using manipulators to control aspects like width, precision, and alignment.

				
					#include <iostream>
#include <iomanip>

int main() {
    double num = 3.14159;
    std::cout << std::setw(10) << std::setprecision(2) << std::fixed << num << std::endl;
    return 0;
}

				
			
				
					// output //
      3.14

				
			

Explanation:

  • std::setw(10) sets the field width to 10 characters.
  • std::setprecision(2) sets the precision to 2 decimal places.
  • std::fixed ensures that the floating-point number is printed in fixed-point notation.

Understanding basic input/output operations is essential for developing interactive and functional C++ programs. By mastering cin and cout, as well , you can create programs that can both receive user input and produce meaningful output, making your applications more versatile and user-friendly.Happy coding! ❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India