Basic Input / Output in C++
In C++, data is read and written using streams, which are sequences of bytes.
- Input stream: Data flows from a device (like the keyboard) to the computer’s memory.
- Output stream: Data flows from memory to an output device (like the screen).
- These streams are defined in the <iostream> header file.
- The most common stream objects are - cin : for taking input, cout : for displaying output.
Standard Output Stream - cout
coutis an instance of theostreamclass used to display output on the screen.- Data is sent to
coutusing the insertion operator<<.
#include <iostream>
using namespace std;
int main()
{
// Printing the given text using cout
cout << "GeeksforGeeks";
return 0;
}
Output
GeeksforGeeks
Standard Input Stream - cin
- cin is an instance of the istream class used to read input from the keyboard.
- The extraction operator >> is used with cin to get data from the input stream and store it in a variable.
#include <iostream>
using namespace std;
int main()
{
int age;
// Taking input from user and store it in variable
cin >> age;
// Output the entered age
cout << "Age entered: " << age;
return 0;
}
Output
18 (Enter by user) Your age is: 18
Un-buffered Standard Error Stream - cerr
- cerr is the standard error stream used to display error messages. It is an instance of the ostream class.
- cerr displays messages immediately, without waiting (Unbuffered output)
- Useful for showing errors or warnings separately from normal program output (cout).
- Unlike cout, which may delay output due to buffering, cerr ensures errors are seen instantly.
Note: The main difference between cerr and cout comes when you would like to redirect output using "cout" that gets redirected to file if you use "cerr" the error doesn't get stored in file.(This is what un-buffered means ..It cant store the message)
#include <iostream>
using namespace std;
int main()
{
cerr << "An error occurred";
return 0;
}
Error
An error occurredBuffered Standard Error Stream - clog
- clog is the standard logging stream used to display error or log messages. It is an instance of the ostream class, like cerr.
- Messages are first stored in a buffer and displayed only when the buffer is full or explicitly flushed using flush() (Buffered output)
- Useful for logging messages that don’t need to appear immediately on the screen.
- Unlike cerr, output from clog may be delayed due to buffering.
#include <iostream>
using namespace std;
int main()
{
clog << "An error occurred";
return 0;
}
Error
An error occurredRead related article Difference between cerr and clog