Input and output streams are used to read and write data through devices such as keyboards, screens, and files. The <iostream> header provides standard stream objects for performing these operations.
- cin reads input, while cout displays output.
- cerr and clog are used to display error and logging messages.
- The >> and << operators are used for formatted input and output.
Example: Program to demonstrate input and output in C++:
#include <iostream>
using namespace std;
int main(){
int age;
// Read input from user
cin >> age;
// Display output
cout << "Age: " << age;
return 0;
}
Output:
18
Age: 18
Explanation: The cin object reads the value entered by the user, while cout displays the stored value.
Types of Standard Streams
C++ provides four commonly used standard stream objects through the <iostream> header.
1. Standard Output Stream – cout
The cout object is an instance of std::ostream used to display standard output, usually on the screen. It uses the insertion operator (<<) to write data.
Syntax:
cout << value;
#include <iostream>
using namespace std;
int main(){
// Display a message
cout << "GeeksforGeeks";
return 0;
}
Output
GeeksforGeeks
2. Standard Input Stream – cin
The cin object is an instance of std::istream used to read standard input, usually from the keyboard. It uses the extraction operator (>>) to read formatted data.
Syntax:
cin >> variable;
#include <iostream>
using namespace std;
int main(){
int num;
// Read an integer
cout << "Enter a number: ";
cin >> num;
cout << "Number: " << num;
return 0;
}
Output:
Enter a number: 25
Number: 25
Explanation: The cin object reads the entered integer and stores it in num, which is then displayed using cout.
3. Standard Error Stream – cerr
The cerr object is an instance of std::ostream used to display error messages. The stream has the unitbuf setting enabled by default, which causes it to flush after each output operation.
Syntax:
cerr << error_message;
#include <iostream>
using namespace std;
int main(){
int divisor = 0;
// Display an error message
if (divisor == 0){
cerr << "Error: Division by zero";
return 1;
}
return 0;
}
Output:
Error: Division by zero
Explanation: The cerr object writes the error message to the standard error stream instead of standard output.
4. Standard Logging Stream – clog
The clog object is an instance of std::ostream used for logging messages. Unlike cerr, it does not have automatic flushing after every output operation enabled by default.
Syntax:
clog << log_message;
#include <iostream>
using namespace std;
int main(){
// Display a log message
clog << "Log: Program started" << endl;
cout << "Program running";
return 0;
}

