Learning Hub Search Ctrl K

Legacy C++ › 5. Exceptions, Strings and I/O

Streams and Formatting

cin/cout, manipulators and stringstream.

beginner #iostream#cout#cin#manipulators#stringstream#formatting

Explanation

The stream library models input and output as flows of characters:

  • std::cout (output), std::cin (input), std::cerr (unbuffered errors), std::clog (buffered log).
  • << inserts, >> extracts; both chain. >> skips leading whitespace and stops at whitespace.
  • std::getline(std::cin, line) reads a whole line.
  • Manipulators (<iomanip>, <ios>) change formatting: std::setw, std::setprecision, std::fixed, std::hex, std::boolalpha, std::endl (newline + flush; '\n' is usually enough).
  • A stream has state flags: good(), eof(), fail(), bad(). A failed extraction leaves the stream in the fail state, and further reads do nothing until clear().
  • std::stringstream brings the same interface to strings in memory.

Example

#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::cout << std::fixed << std::setprecision(2);
    std::cout << std::setw(8) << 3.14159 << "|" << std::setw(8) << std::left << 2.5 << "|\n";
    std::cout << std::hex << 255 << " " << std::dec << 255 << " "
              << std::boolalpha << true << "\n";

    // read numbers from a string, tolerating bad input
    std::istringstream in("10 20 abc 30");
    int n, sum = 0;
    while (in >> n) sum += n;                 // stops at "abc"
    std::cout << "sum=" << sum << "\n";       // 30
    in.clear();                               // reset the fail flag
    std::string bad;
    in >> bad;                                // "abc"
    std::cout << "skipped " << bad << "\n";

    std::string line;
    std::cout << "Your name? ";
    if (std::getline(std::cin, line))
        std::cout << "Hello, " << line << "\n";
    else
        std::cout << "\n(no input)\n";
    return 0;
}

Common pitfalls

  • Looping while (!in.eof()) processes the last item twice. Test the extraction itself: while (in >> n).
  • Mixing >> and getline: >> leaves the newline in the buffer, so the next getline returns an empty string. Call std::cin.ignore(...) first.
  • Forgetting clear() after a failed read leaves the stream stuck.
  • std::endl flushes every time and is slow in tight loops.
  • Formatting flags such as std::hex and std::setprecision are sticky; reset them.

Legacy vs modern

C++11 adds std::stoi, std::to_string, and the std::put_time/get_money helpers; C++20 std::format and C++23 std::print offer type-safe, printf-like formatting. See std::format and std::span.

Exercises

1. Why does std::cin >> x; followed by std::getline(std::cin, s); often read an empty string?

The newline after the number is still in the input buffer, so getline consumes just that newline. Discard it with std::cin.ignore(1000, '\n');.