Skip to content
C++

I/O Streams — Quick Reference

C++ I/O streams cheatsheet — cin/cout/cerr, file streams, string streams, formatting, error handling, binary I/O, and performance tips.

Standard Streams

cpp
#include <iostream>

// Output
std::cout << "value: " << 42 << "\n";     // buffered stdout
std::cerr << "error: " << msg << "\n";    // unbuffered stderr
std::clog << "log: "   << msg << "\n";    // buffered stderr

// Input
int n;
std::cin >> n;                             // read int, skip whitespace
std::string word;
std::cin >> word;                          // read word (stop at whitespace)
std::string line;
std::getline(std::cin, line);             // read full line including spaces
std::getline(std::cin, line, ',');        // read up to delimiter ','

std::println (C++23, preferred)

cpp
#include <print>
std::println("hello {}", name);           // + newline
std::print("partial line {}", x);         // no newline
std::println(std::cerr, "error: {}", e);  // to stream

File I/O (fstream)

cpp
#include <fstream>

// Write a file
{
    std::ofstream out{"output.txt"};
    if (!out) throw std::system_error(errno, std::generic_category());
    out << "line 1\n" << "line 2\n";
}  // auto-closed on scope exit

// Read a file line by line
{
    std::ifstream in{"input.txt"};
    for (std::string line; std::getline(in, line); ) {
        process(line);
    }
}

// Read entire file to string
std::string slurp(const char* path) {
    std::ifstream f{path};
    return {std::istreambuf_iterator<char>{f}, {}};
}

// Append mode
std::ofstream log{"app.log", std::ios::app};

Error Checking

cpp
std::ifstream f{"missing.txt"};
if (!f) { std::println(stderr, "failed to open"); return; }
if (!f.good()) { /* any error */ }
if (f.fail())  { /* logic error (bad format) */ }
if (f.bad())   { /* I/O error */ }
if (f.eof())   { /* end of file */ }

// Throw on error (enable exceptions)
f.exceptions(std::ios::failbit | std::ios::badbit);
// Now operations throw std::ios_base::failure on error

Binary I/O

cpp
// Write binary
std::ofstream out{"data.bin", std::ios::binary};
uint32_t value = 0xDEADBEEF;
out.write(reinterpret_cast<const char*>(&value), sizeof(value));

std::vector<int> vec = {1, 2, 3, 4, 5};
out.write(reinterpret_cast<const char*>(vec.data()),
          vec.size() * sizeof(int));

// Read binary
std::ifstream in{"data.bin", std::ios::binary};
uint32_t v;
in.read(reinterpret_cast<char*>(&v), sizeof(v));

// File size
in.seekg(0, std::ios::end);
auto size = in.tellg();
in.seekg(0, std::ios::beg);

String Streams

cpp
#include <sstream>

// Build string from parts (pre-C++20; prefer std::format now)
std::ostringstream oss;
oss << "Point(" << x << ", " << y << ")";
std::string s = oss.str();

// Parse from string
std::istringstream iss{"10 20 30"};
int a, b, c;
iss >> a >> b >> c;

// Check parse success
if (!(iss >> a)) { /* parse failed */ }

// Reuse: clear state and set new content
iss.clear();
iss.str("1.5 2.5");

Formatting Output

cpp
#include <iomanip>

// Width and fill
std::cout << std::setw(10) << std::right << 42 << "\n";  // "        42"
std::cout << std::setw(10) << std::left  << "hi" << "\n";// "hi        "
std::cout << std::setfill('0') << std::setw(5) << 42;    // "00042"

// Numeric bases
std::cout << std::hex << 255 << "\n";      // ff
std::cout << std::oct << 255 << "\n";      // 377
std::cout << std::dec << 255 << "\n";      // 255 (restore decimal)
std::cout << std::showbase << std::hex << 255;  // 0xff

// Floating point
std::cout << std::fixed      << std::setprecision(2) << 3.14159;  // 3.14
std::cout << std::scientific << 3.14159;   // 3.141590e+00

Performance Tips

cpp
// Sync stdio off (3–5× faster, but don't mix printf/cout after)
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);    // don't flush cout before each cin

// Prefer printf/puts for hot-path output
// Prefer std::print (C++23) over cout chains

// Avoid endl (flushes): use "\n" instead
std::cout << result << "\n";   // fast
std::cout << result << std::endl;  // slow — forces flush
Edit on GitHub