Streams
Prerequisites
1. What is a Stream?
A stream in C++ is an abstraction for input/output operations.
1
| [ Source ] → (Input Stream) → Program → (Output Stream) → [ Destination ]
|
1
2
3
4
5
6
7
| std::ios
│
┌──────┴────────────┐
std::istream std::ostream
│ │
std::ifstream std::ofstream
std::istringstream std::ostringstream
|
All streams are built on top of std::ios
Used for input operations
Example
1
2
3
4
| #include <iostream>
int x;
std::cin >> x;
|
std::cin is an instance of std::istream
1
2
3
4
| std::cin >> x; // extraction
std::cin.get(); // get character
std::cin.ignore(); // skip input
std::cin.peek(); // look ahead
|
std::ostream (Output Stream)
Used for output operations
Example
1
2
3
| #include <iostream>
std::cout << "Hello";
|
std::cout is an instance of std::ostream
1
2
3
| std::cout << x; // insertion
std::cout.put('A'); // write character
std::cout.flush(); // force output
|
Reads data from a file.
Example
1
2
3
4
5
6
| #include <fstream>
std::ifstream file("data.txt");
int x;
file >> x;
|
1
2
3
4
| if (!file)
{
std::cout << "Failed to open file\n";
}
|
std::ofstream (File Output Stream)
1
2
3
4
5
| #include <fstream>
std::ofstream file("output.txt");
file << "Hello file";
|
Treats a string like an input stream.
Example
1
2
3
4
5
6
7
8
| #include <sstream>
std::string data = "10 20 30";
std::istringstream iss(data);
int a, b, c;
iss >> a >> b >> c;
|
Useful for parsing strings
std::ostringstream (String Output Stream)
1
2
3
4
5
6
7
| #include <sstream>
std::ostringstream oss;
oss << "Value: " << 10;
std::string result = oss.str();
|
std::streambuf (Core of Streams)
The actual buffer layer behind all streams
1
2
3
4
5
| [ Stream (iostream) ]
↓
[ streambuf (buffer) ]
↓
[ Device (file, console, string) ]
|
- controls actual I/O behavior
- handles buffering
- used for custom stream implementations
Example: Access buffer
1
| std::streambuf* buf = std::cout.rdbuf();
|
Redirect Output
1
2
3
4
5
6
7
8
| #include <fstream>
std::ofstream file("log.txt");
std::streambuf* old = std::cout.rdbuf(file.rdbuf());
std::cout << "This goes to file\n";
std::cout.rdbuf(old); // restore
|
Streams are slower than C-style I/O
vs
- type safety
- formatting
- abstraction overhead
Disable sync with C I/O
1
2
| std::ios::sync_with_stdio(false);
std::cin.tie(nullptr); // stop cout.flush
|
Huge speed boost for competitive programming
| Type | Purpose |
|---|
istream | input |
ostream | output |
ifstream | file input |
ofstream | file output |
istringstream | string input |
ostringstream | string output |
streambuf | buffer layer |
3. Common Mistakes
❌ Mixing cin and getline
1
2
| std::cin >> x;
std::getline(std::cin, str); // ❌ leftover newline
|
✔️ Fix:
1
2
3
| std::cin >> x;
std::cin.ignore(); // remove newline
std::getline(std::cin, str);
|
❌ Not flushing output when needed
1
| std::cout << "Waiting...";
|
👉 May not appear immediately
✔️ Fix:
1
| std::cout << "Waiting..." << std::flush;
|