C++
Module 6: Input and OutputBeginner40 min read

C++ Streams (cout, cin, cerr, clog), getline() & iomanip Formatting

Master standard I/O streams, reading full lines with getline(), formatting numbers with <iomanip>, and clearing input buffer errors.

Key Takeaways & Core Concepts
  • `std::cout`: Buffered standard output (<< insertion).
  • `std::cin`: Standard input (>> extraction).
  • `std::cerr`: Unbuffered standard error (flushes immediately—ideal for critical errors).
  • `std::clog`: Buffered standard logging stream.

1. Standard I/O Streams (`<iostream>`)

  • `std::cout`: Buffered standard output (<< insertion).
  • `std::cin`: Standard input (>> extraction).
  • `std::cerr`: Unbuffered standard error (flushes immediately—ideal for critical errors).
  • `std::clog`: Buffered standard logging stream.
1. Aligned Table Formatting with iomanip
1#include <iostream>
2#include <iomanip>
3
4int main() {
5 std::cout << std::left << std::setw(12) << "Item" << std::right << std::setw(8) << "Price" << "\n";
6 std::cout << std::fixed << std::setprecision(2);
7 std::cout << std::left << std::setw(12) << "C++ Book" << std::right << std::setw(8) << 499.5 << "\n";
8 return 0;
9}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
9 lines
Note: Combines `setw`, `left`/`right` alignment, `fixed`, and `setprecision(2)`.

2. `getline()`, Input Buffer & Error Recovery

std::cin >> s stops at whitespace. Use std::getline(std::cin, s) for full lines. When switching from cin >> num to getline(), clear the leftover newline with std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');. If invalid input puts cin into fail state, call std::cin.clear() before ignore().

3. Formatting with `<iomanip>`

std::fixed, std::scientific, std::setprecision(n), std::setw(w), std::left / std::right, std::showpoint.

Practice & AssessmentC++ Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)