Lesson 209 +5 XP

<iostream> Objects Reference

&lt;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

ObjectTypeDirectionWhat it does
coutstd::ostreamoutprints text to the console
cinstd::istreaminreads text typed at the console
cerrstd::ostreamoutprints errors to the console
clogstd::ostreamoutprints 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 like cout, 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); use endl when 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> for std::string.
  • After a cin >> x, an Enter may be left behind. Add cin.ignore(); before getline to swallow it.

Stream state: the lazy fix

  • cin.fail() is true after a bad read (e.g. typing a letter where a number goes).
  • cin.clear() resets the failed flag so cin works again.
  • cin.ignore() discards whatever junk is left in the buffer.

Notes

  • cout, while in the iostream` header, needs using namespace std; or a std::` prefix.
  • cerr is 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

  • cout prints, cin reads, cerr/clog print errors/logs.
  • << sends output; >> reads input.
  • endl = newline + flush; flush = flush only.
  • Wait for cin >> to skip spaces text, so prefer getline(cin, line).