std::cout << "value: " << 42 << "\n";
int x; std::cin >> x;
C++
Topics in this category
Casting & Conversions
Compilation & Linking
Concepts & Constraints
Concurrency
Const Correctness
Constexpr & Compile-Time
Coroutines
Enums & Enum Classes
Exception Handling
I/O Streams
Lambda Expressions
Memory Management
Modern C++
Move Semantics
Namespaces
OOP & Classes
Operator Overloading
Preprocessor & Macros
RAII & Smart Pointers
Ranges & Views
C++
I/O Streams
C++ streams are a type-safe, extensible I/O abstraction in <iostream>: std::cin (input), std::cout (output), std::cerr (unbuffered error), and std::clog (buffered log). They use operator<< (insertion) and operator>> (extraction), which are overloadable for user types, unlike C's printf/scanf format strings.
Real-world example
A program reads user input with std::cin and prints results with std::cout using overloaded operators.
Operator Overloading
I/O Streams
I/O Streams
std::cout is the standard output stream (buffered). std::cerr is the standard error stream, unbuffered so messages appear immediately (good for errors). std::clog is also for logging to standard error but buffered (more efficient for high-volume logs). Separating normal output from errors lets them be redirected independently.
std::cout << "result\n";
std::cerr << "error!\n"; // immediate, unbuffered
Real-world example
Errors go to std::cerr so they still appear even if stdout is redirected to a file.
I/O Streams
I/O Streams
I/O Streams
std::ifstream opens a file for reading and std::ofstream for writing; std::fstream does both. They're RAII—opening in the constructor and closing in the destructor—and use the same << / >> and getline as other streams. Always check that the stream opened successfully before using it.
std::ifstream in("data.txt");
if (!in) { /* handle error */ }
std::string line;
while (std::getline(in, line)) { /* process */ }
Real-world example
A config loader reads lines from an ifstream, which closes automatically via RAII when it goes out of scope.
RAII & Smart Pointers
I/O Streams
I/O Streams
operator>> extracts formatted, whitespace-delimited tokens (skipping leading whitespace and stopping at the next whitespace), good for reading numbers/words. std::getline reads an entire line (up to a delimiter, default newline) including spaces. Mixing them requires care because >> leaves the trailing newline in the buffer, which getline then reads as empty.
int n; std::cin >> n;
std::cin.ignore(); // discard leftover newline
std::string line; std::getline(std::cin, line);
Real-world example
Reading a number then a full line requires ignoring the leftover newline between >> and getline.
I/O Streams
Strings & string_view
I/O Streams
Streams have state flags: good(), eof() (end of file reached), fail() (format/logic error), and bad() (serious error). A stream is convertible to bool (true if not failed), so you can write while (stream >> x) or if (stream). Use clear() to reset error flags after handling an error.
int x;
while (std::cin >> x) { /* uses valid x */ }
if (std::cin.fail()) { std::cin.clear(); }
Real-world example
A robust input loop stops on bad input using the stream's bool conversion and then clears the error.
I/O Streams
Exception Handling
I/O Streams
Manipulators are objects/functions that change stream formatting: std::endl (newline + flush), std::setw/std::setprecision/std::fixed (from <iomanip>), std::hex/std::dec, std::boolalpha, and std::flush. They're inserted into the stream to control width, precision, base, and formatting of subsequent output.
std::cout << std::fixed << std::setprecision(2) << 3.14159; // 3.14
Real-world example
A report formats currency with std::fixed and setprecision(2) for consistent decimal places.
I/O Streams
Strings & string_view
I/O Streams
'\n' inserts a newline character. std::endl inserts a newline AND flushes the stream's buffer. Flushing forces output immediately but is comparatively expensive; overusing std::endl in loops hurts performance. Prefer '\n' for normal output and reserve std::endl (or std::flush) for when you truly need an immediate flush.
std::cout << "line\n"; // fast
std::cout << "line" << std::endl; // newline + flush (slower)
Real-world example
Replacing std::endl with '\n' in a tight logging loop noticeably speeds up output.
I/O Streams
I/O Streams
I/O Streams
Define a free function operator<< taking std::ostream& and a const reference to your type, writing the members to the stream and returning the stream (to allow chaining). It's usually a non-member (often friend) so the stream is the left operand. This integrates your type with all output streams.
std::ostream& operator<<(std::ostream& os, const Point& p){
return os << "(" << p.x << ", " << p.y << ")";
}
Real-world example
Overloading operator<< for a Point lets it be printed directly with std::cout like a built-in type.
Operator Overloading
I/O Streams
I/O Streams
std::stringstream (and ostringstream/istringstream) is an in-memory stream backed by a std::string. It's used to build formatted strings, parse strings into typed values, and convert between text and numbers using the familiar << / >> operators—handy for tokenizing input or assembling output without file/console I/O.
std::ostringstream oss;
oss << "x=" << 5;
std::string s = oss.str(); // "x=5"
Real-world example
A logger assembles a formatted message in an ostringstream before writing it out in one call.
Strings & string_view
I/O Streams
I/O Streams
Techniques: call std::ios_base::sync_with_stdio(false) to decouple C++ streams from C stdio (faster but don't mix them then); untie cin from cout (std::cin.tie(nullptr)) to avoid flushing cout before each read; avoid std::endl (use '\n'); read in bulk; and for heavy formatting, prefer std::format or from_chars/to_chars. These reduce per-operation overhead.
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
Real-world example
Competitive/large-data programs disable sync_with_stdio to speed up millions of cin/cout operations.
I/O Streams
Strings & string_view
I/O Streams