Skip to content
Tutorials Center
My learning

Topics

Lesson 122 of 171 ยท Input/Output and Files

I/O Streams in Depth

Master C++ I/O streams - the iostream class hierarchy, cin, cout, cerr and clog, fail/eof/bad state flags, recovering from bad input, manipulators and fast I/O.

Most new C++ code prints with std::println, but iostreams are everywhere: in existing code bases, in textbooks, in competitive programming, and in every program that reads input with std::cin. They're also the foundation for files and string streams, which use exactly the same interface. You met std::cout and std::cin briefly in Printing Output and Reading User Input; this lesson explains how they really work.

You'll learn how the stream classes fit together, how the four standard streams differ, how a stream remembers that something went wrong (and how to recover), how manipulators control formatting, and the two lines that make stream I/O fast.

The stream class hierarchy

A stream is an object that moves characters between your program and somewhere else: the console, a file, a string. The classes are templates on the character type, but you almost always use the char versions through these names:

Class Header Purpose
std::ios_base, std::ios <ios> Shared state: format flags, precision, error state
std::istream <istream> Input: >>, get, getline, read
std::ostream <ostream> Output: <<, put, write, flush
std::iostream <istream> Both directions
std::ifstream, std::ofstream, std::fstream <fstream> Files
std::istringstream, std::ostringstream, std::stringstream <sstream> Strings in memory

Because std::ofstream derives from std::ostream, any function that takes std::ostream& can write to the console, a file or a string without changing a line. That's the main design idea of iostreams:

C++
void write_report(std::ostream& out);   // works with std::cout, a file, or a std::ostringstream

Underneath, each stream owns a stream buffer (std::streambuf) that does the actual reading and writing. The stream on top handles formatting and error state. You rarely touch the buffer directly, but rdbuf() gives access to it, which is handy for tricks like copying a whole file.

The four standard streams

<iostream> declares four global stream objects, ready when main starts:

  • std::cin: standard input (an istream).
  • std::cout: standard output, buffered. Characters collect in memory and are written in chunks.
  • std::cerr: standard error, unbuffered. Every output operation is written immediately, which is what you want for error messages and crash diagnostics.
  • std::clog: also standard error, but buffered. Use it for high-volume logging where speed matters more than immediacy.

std::cin is tied to std::cout: before cin reads anything, it flushes cout. That's why a prompt printed without a newline still appears before the program waits for input.

C++ cout, cerr, clog and the cin tie

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Standard output and standard error are separate channels. On a terminal they're mixed together, but ./app > out.txt sends only cout to the file while errors still reach the screen. Our editor shows stdout and stderr as separate sections.

std::endl versus '\n'

std::endl writes a newline and flushes the stream. Flushing is a system call, and doing it on every line can make output-heavy programs many times slower. Write '\n' by default and flush only when you need the output visible right now (std::flush or std::cout.flush()). The same advice holds for std::println, which never flushes on its own.

Stream state: good, fail, eof and bad

Every stream carries a small set of state flags that record what went wrong:

Flag Set when Check with
eofbit An operation reached the end of input eof()
failbit An operation failed: the input didn't match the expected format, or nothing was left to read fail()
badbit A serious, usually unrecoverable error, such as a failed device read bad()
(none) Everything is fine good()

Two facts make streams pleasant to use. First, >> returns the stream itself, so you can chain reads. Second, a stream converts to bool: it's true when neither failbit nor badbit is set. That's why if (std::cin >> x) and while (std::cin >> x) work.

The most important rule: once a stream has failed, every later operation does nothing until you clear the error. Watch the flags change:

C++ Watching the state flags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The output tells the whole story:

  • Reading 42 succeeds and the stream stays good.
  • Reading abc as an int sets failbit. Since C++11, a failed numeric extraction stores 0 in the variable. The characters abc stay in the input.
  • The next >> does nothing at all; n keeps the -1 we put there.
  • After clear() and skipping the bad word, 7 is read and the stream is good again.
  • Reading again finds only the final newline. Skipping whitespace runs into the end of input, so eofbit and failbit are both set. This time n keeps its -1: the read gave up before it even started parsing a number, so nothing was stored.

That last point explains a classic bug. while (!std::cin.eof()) is the wrong loop condition: eof is only set after a read hits the end, so the loop body runs once too often with a failed read. Test the read itself instead.

Reading until the end and recovering from bad input

The idiomatic input loop puts the read in the condition. When it stops, you can ask why: end of input, or bad data?

C++ Summing numbers until input runs out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The loop stops at x, so the result is 4 numbers with a total of 54. Remove the x from the Input box and run it again to see the end-of-input message with all five numbers.

To recover and keep reading, you need two steps: clear() resets the flags, and ignore() throws away the bad characters. std::cin.ignore(n, '\n') discards up to n characters or through the next newline; passing std::numeric_limits<std::streamsize>::max() means "no limit".

C++ Asking again until the input is valid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Because the Input box isn't echoed like a real terminal, the prompts and messages appear on one line each, followed by Accepted 42%. In a terminal, the user's typing would appear between them.

Streams can also throw instead of setting flags quietly: std::cin.exceptions(std::ios::failbit | std::ios::badbit) makes a failed operation throw std::ios_base::failure. It's rarely used for interactive input, but it can simplify code that reads files which must be well-formed.

Formatting with manipulators

Manipulators are objects you insert into a stream to change how it formats values. Those without arguments are in <ios>/<iostream>; those with arguments, like std::setw(10), are in <iomanip>.

Manipulator Effect Sticky?
std::setw(n) Minimum width of the next field No, resets after one item
std::setfill(c) Padding character Yes
std::left, std::right, std::internal Alignment inside the width Yes
std::fixed, std::scientific, std::defaultfloat Floating-point notation Yes
std::setprecision(n) Significant digits, or digits after the point with fixed/scientific Yes
std::hex, std::oct, std::dec Integer base Yes
std::showbase, std::uppercase, std::showpos 0x prefix, upper-case digits, + sign Yes
std::boolalpha Print true/false instead of 1/0 Yes

"Sticky" means the setting stays until you change it. That's the biggest trap with manipulators: a std::hex in one function silently affects every number printed later.

C++ Manipulators for a formatted table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

39.999 prints as 40.00, rounded to two decimals. The last line shows 3.142: four significant digits, because defaultfloat is back.

Saving and restoring the format state

A function that changes sticky flags on a stream it was given should put them back. The simplest portable way is to save the flags, precision and fill, then restore them:

C++
void print_hex(std::ostream& out, unsigned value) {
    auto old_flags = out.flags();          // std::ios_base::fmtflags
    auto old_fill = out.fill();
    out << std::hex << std::setw(8) << std::setfill('0') << value << '\n';
    out.flags(old_flags);
    out.fill(old_fill);
}

out.copyfmt(saved) with a scratch std::ios saved(nullptr) does the same in one call. Or avoid the problem entirely with std::format/std::println, which keep their formatting in the format string and never change the stream: std::println(out, "{:08x}", value). The format-spec mini-language is covered in Formatting with std::format and std::print.

Making stream I/O fast

By default, C++ streams are synchronized with C's stdio (printf, scanf), so you can mix both freely. That synchronization makes std::cin and std::cout slow, and cin also flushes cout before every read because of the tie. Programs that read millions of numbers (competitive programming is the classic case) start with these two lines:

C++
int main() {
    std::ios::sync_with_stdio(false);   // stop syncing with printf/scanf
    std::cin.tie(nullptr);              // don't flush cout before every cin read
    // ... fast reading and writing ...
}

Call them before any I/O. Afterwards, don't mix printf/scanf with cout/cin on the same stream: their outputs may come out in the wrong order. And since prompts are no longer flushed automatically, flush them yourself in interactive programs.

Combined with '\n' instead of std::endl, this often makes stream I/O as fast as C's.

Redirecting streams

std::cout doesn't know whether it's writing to a terminal, a file or a pipe. That's decided outside your program, or by swapping the buffer underneath the stream. There are three levels at which you can redirect.

In the shell

The simplest redirection needs no code at all. The shell connects the program's standard streams before it starts:

Terminal
./report > out.txt            # std::cout (stdout) into a file
./report 2> errors.txt        # std::cerr and std::clog (stderr) into a file
./report > all.txt 2>&1       # both into the same file
./report < input.txt          # std::cin reads the file
./report | sort | head -5     # stdout feeds another program

This is the reason to send diagnostics to std::cerr: when a user redirects the output to a file, error messages still appear on the screen and don't corrupt the data. It's also why output can look different when redirected: a terminal gets line-buffered output, while a file or pipe gets full buffering, which matters if the program crashes before flushing.

Inside the program with rdbuf()

Every stream does its actual reading and writing through a std::streambuf. rdbuf() returns that buffer, and rdbuf(new_buffer) installs a different one and returns the old one. Point std::cout at a string stream's buffer and everything printed with std::cout lands in a string; point std::cin at an std::istringstream and the program reads prepared text. This is a standard trick for testing functions that use std::cin and std::cout directly. Because forgetting to restore the buffer leaves std::cout pointing at a destroyed object, wrap the swap in a small RAII class:

C++ Capturing cout and feeding cin with rdbuf

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

greet_users ran unchanged, reading three names from the string and writing 40 characters into captured. Notice the first line of output: std::println was not captured. std::print, std::println and printf write to C's stdout, not through std::cout's buffer, so swapping std::cout's buffer doesn't affect them. The same applies to code in C libraries. Destruction order matters too: the redirect objects are destroyed (and the buffers restored) before captured and fake_input, because they were declared after them. (A better long-term design is to give functions a std::ostream& and std::istream& parameter, as shown at the start of this lesson, so tests can pass string streams directly.)

Redirecting the C streams with freopen

To redirect everything that goes to standard output, including printf and std::println, redirect C's stdout itself with std::freopen(path, mode, stdout) from <cstdio>. Because std::cout is synchronized with stdout by default, it follows along. The catch: standard C++ has no portable way to get the original console back afterwards (POSIX code can save and restore the descriptor with dup and dup2), so freopen suits programs that redirect once, at startup, for example to log to a file when started without a terminal.

C++ Redirecting to files with rdbuf and freopen

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

With rdbuf, only the std::cout line went into cout.log while printf stayed on the screen. After freopen, all three ways of printing ended up in all.log, and the program has to use std::cerr to show the result, because standard output is gone for good. The std::fflush and std::flush calls before each switch make sure text already buffered goes to the old destination, not the new one.

Technique Affects Undo? Typical use
Shell >, 2>, <, | The whole process Not needed Normal usage, scripts, pipelines
stream.rdbuf(buffer) One C++ stream only Yes, restore the old buffer Tests, capturing a library's std::cout output
std::freopen(..., stdout) C stdout and the synced std::cout Not portably Redirect once at startup, logging

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Input is abc. After int n = 5; std::cin >> n;, what are n and std::cin.fail()?

    A failed numeric extraction sets failbit and, since C++11, stores 0 in the variable. Exceptions are only thrown if you enable them with exceptions().
  2. 2. A read failed, and the program immediately calls std::cin >> n again without anything else. What happens?

    The stream stays in the failed state. You need clear() and usually ignore() to skip the bad input.
  3. 3. What does std::cout << std::setw(6) << 42 << 7; print?

    setw is the one manipulator that isn't sticky; it resets to 0 after the next formatted output.
  4. 4. Why is while (!std::cin.eof()) { std::cin >> x; sum += x; } buggy?

    Put the read in the condition, as in while (std::cin >> x), so the body only runs after a successful read.
  5. 5. What do std::ios::sync_with_stdio(false); std::cin.tie(nullptr); do?

    They remove two sources of overhead. Afterwards, don't mix C stdio with the same streams, and flush prompts yourself.

Summary

  • iostreams form a hierarchy: functions taking std::ostream& or std::istream& work with the console, files and strings alike.
  • cout and clog are buffered, cerr is unbuffered, and cin is tied to cout so prompts appear before reads.
  • Streams keep state flags (eof, fail, bad); a stream is true when not failed, and a failed stream ignores operations until clear().
  • Loop with while (std::cin >> x), never while (!eof()); recover with clear() plus ignore().
  • Manipulators format output; all except setw are sticky, so restore them or prefer std::format.
  • Prefer '\n' over std::endl; sync_with_stdio(false) and cin.tie(nullptr) speed up heavy I/O.

Next: Reading and Writing Text Files, where the same stream skills work on files.