I/O Streams: cin, cout, formatting

ইনপুট ও আউটপুট — cin, cout, format

Read: ~30 min 10 practice problems

1. The Big Three Streams

StreamDirectionUse
std::cinInputRead from keyboard
std::coutOutputPrint to screen (buffered)
std::cerrOutputError messages (unbuffered)

2. Reading Input with std::cin

read.cpp
#include <iostream>
#include <string>

int main() {
    int age;
    double height;
    std::string name;

    std::cin >> age >> height >> name;

    std::cout << "Name: " << name << "\n";
    std::cout << "Age: "  << age  << "\n";
    std::cout << "Height: " << height << "\n";
}
cin gotcha std::cin >> word stops at whitespace. To read a whole line including spaces, use std::getline(std::cin, line).

3. Reading Whole Lines

getline.cpp
#include <iostream>
#include <string>

int main() {
    std::string full_name;
    std::getline(std::cin, full_name);
    std::cout << "Hello, " << full_name << "!\n";
}

4. Formatted Output with <iomanip>

format.cpp
#include <iostream>
#include <iomanip>

int main() {
    double pi = 3.14159265;
    std::cout << std::fixed << std::setprecision(2) << pi << "\n";     // 3.14
    std::cout << std::setw(10) << 42 << "|\n";                           //         42|
    std::cout << std::left << std::setw(10) << 42 << "|\n";             // 42        |
    std::cout << std::hex << 255 << "\n";                              // ff
    std::cout << std::dec;                                              // reset to decimal
}

5. std::format (C++20) — Modern Way

Python-style format strings, type-safe and concise:

format20.cpp
#include <iostream>
#include <format>

int main() {
    std::string name = "Sara";
    int age = 21;
    std::cout << std::format("Hello {}, age {}\n", name, age);
    std::cout << std::format("Pi = {:.3f}\n", 3.14159);
    std::cout << std::format("Hex of 255 = {:#x}\n", 255);
}

6. Stream State & Error Handling

If input fails (e.g. user types text where number expected), the stream's fail bit is set:

state.cpp
#include <iostream>

int main() {
    int n;
    if (!(std::cin >> n)) {
        std::cerr << "Invalid input!\n";
        return 1;
    }
    std::cout << "You entered " << n << "\n";
}

7. Practice Problems

  1. Read two integers and print their sum.
    ✨ Show Answer
    sum.cpp
    #include <iostream>
    int main() {
        int a, b;
        std::cin >> a >> b;
        std::cout << a + b << "\n";
    }
  2. Why use std::cerr instead of std::cout for errors?
    ✨ Show Answer

    std::cerr is unbuffered (writes immediately) and shells redirect it separately (2> vs 1>). Errors should always go to cerr so they are visible even if the program crashes.

  3. Read a full sentence with spaces.
    ✨ Show Answer

    Use std::getline(std::cin, str); — cin >> str stops at whitespace.

  4. Print pi with 5 digits after the decimal.
    ✨ Show Answer
    std::cout << std::fixed << std::setprecision(5) << 3.14159265;
  5. Print 7 in hex, octal, and decimal.
    ✨ Show Answer
    std::cout << std::hex << 7 << " "
              << std::oct << 7 << " "
              << std::dec << 7 << "\n"; // 7 7 7
  6. What does std::cout.flush() do?
    ✨ Show Answer

    Forces the buffered output to be written immediately. Useful when debugging crashes — output that wasn't flushed will be lost.

  7. Using std::format, format pi as "3.142".
    ✨ Show Answer
    std::cout << std::format("{:.3f}", 3.14159);
  8. Why is std::endl often slower than "\n"?
    ✨ Show Answer

    It writes a newline AND flushes. Flushing forces an OS write call. "\n" only writes a newline.

  9. Read 5 numbers in a loop and print their average.
    ✨ Show Answer
    avg.cpp
    #include <iostream>
    int main() {
        double sum = 0, x;
        for (int i = 0; i < 5; ++i) { std::cin >> x; sum += x; }
        std::cout << sum / 5 << "\n";
    }
  10. Speed up cin/cout for competitive programming.
    ✨ Show Answer
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    Disables synchronization with C-style I/O and unties cin from cout. Massive speedup in tight I/O loops.

Summary

Use std::cin and std::cout for type-safe I/O. Use std::getline for whole lines. <iomanip> provides setw, setprecision, hex. C++20's std::format is the modern way — Python-like and type-safe. Always check stream state after reading user input.

Next Module → Control Flow I: if, switch, ternary.