C++

I/O Streams

10 question(s)

What are C++ I/O streams?

Beginner
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.
std::cout << "value: " << 42 << "\n";
int x; std::cin >> x;
Real-world example A program reads user input with std::cin and prints results with std::cout using overloaded operators.

Common follow-ups: What are cin, cout, cerr, clog? | Why are streams type-safe?

Operator Overloading I/O Streams I/O Streams

What is the difference between std::cout, std::cerr, and std::clog?

Beginner
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.

Common follow-ups: Which is unbuffered? | Why separate output from errors?

I/O Streams I/O Streams I/O Streams

How do you read a file with ifstream and write with ofstream?

Intermediate
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.

Common follow-ups: How do you check a file opened? | Which stream closes the file?

RAII & Smart Pointers I/O Streams I/O Streams

What is the difference between >> and std::getline for input?

Intermediate
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.

Common follow-ups: Why does mixing >> and getline cause issues? | What does getline include?

I/O Streams Strings & string_view I/O Streams

How do you check for and handle stream errors?

Beginner
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.

Common follow-ups: What do fail() and eof() mean? | How do you reset error state?

I/O Streams Exception Handling I/O Streams

What are stream manipulators and how are they used?

Advanced
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.

Common follow-ups: What does std::endl do besides newline? | Where do setw/setprecision come from?

I/O Streams Strings & string_view I/O Streams

What is the difference between std::endl and '\n'?

Intermediate
'\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.

Common follow-ups: What extra work does std::endl do? | When is flushing needed?

I/O Streams I/O Streams I/O Streams

How do you overload operator<< for a custom type?

Advanced
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.

Common follow-ups: Why return the stream? | Why is it a non-member function?

Operator Overloading I/O Streams I/O Streams

What is std::stringstream and when is it useful?

Intermediate
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.

Common follow-ups: How do you get the resulting string? | How can it parse input?

Strings & string_view I/O Streams I/O Streams

How do you improve iostream performance for large I/O?

Advanced
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.

Common follow-ups: What does sync_with_stdio(false) do? | Why untie cin from cout?

I/O Streams Strings & string_view I/O Streams