Loading lessons...
<iostream> Objects Reference
<iostream> Objects Reference
The `iostream header (short for "standard input/output stream") is where the magic of cout, cin` and friends lives. Every program that talks to the console needs it.
The four standard stream objects
| Object | Type | Direction | What it does |
|---|---|---|---|
cout | std::ostream | out | prints text to the console |
cin | std::istream | in | reads text typed at the console |
cerr | std::ostream | out | prints errors to the console |
clog | std::ostream | out | prints log messages to the console |
All four live in the std namespace, so you normally write std::cout or add using namespace std;.
Stream objects flush behaviour
cout- "character out". Buffered: output may sit in a buffer until it's flushed.cin- "character in". Blocking; waits for the user to press Enter.cerr- "character error". Unbuffered; error output appears immediately.clog- "character log." Buffered likecout, meant for log messages.
The insertion operator <<
Sends data into a stream. Works with any type that knows how to print itself:
cout << "Total: " << 42 << endl;
<<as an "insertion" operator writes to the output stream.- Chains of
<<print in order, left to right.
The extraction operator >>
Pulls a value out of the INPUT stream:
int age;
cin >> age;
- Waits for the user to type a number and press Enter.
- Skips leading whitespace by default.
- With
>>, the reading stops at the first whitespace - so it's not great for whole sentences.
The endl and flush manipulators
Both push buffered output to the screen. endl also starts a new line:
cout << "One" << endl; // newline + flush
cout << "Two" << flush; // flush, no newline
endl= newline + flush.flush= flush only.- Prefer
'\n'for everyday line breaks (no flush cost); useendlwhen timing matters (progress bars, logs).
Reading a whole line with getline
cin >> stops at whitespace. When you want the whitespace included, use getline:
string name;
getline(cin, name); // reads a whole line, including spaces
- Include
<string>forstd::string. - After a
cin >> x, an Enter may be left behind. Addcin.ignore();beforegetlineto swallow it.
Stream state: the lazy fix
cin.fail()istrueafter a bad read (e.g. typing a letter where a number goes).cin.clear()resets the failed flag socinworks again.cin.ignore()discards whatever junk is left in the buffer.
Notes
cout, while in theiostream`header, needsusing namespace std;or astd::` prefix.cerris for really gone wrong errors;clog` is for routine log messages.- Insertion
<<and extraction>>aren't built-in magic for every type - if you write your own class, you overload them to make it printable.
TL;DR
coutprints,cinreads,cerr/clogprint errors/logs.<<sends output;>>reads input.endl= newline + flush;flush= flush only.- Wait for
cin >>to skip spaces text, so prefergetline(cin, line).