C++ Cheatsheet

Input and Output

Use this C++ reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Standard Streams

ObjectTypePurpose
std::cinistreamstandard input (keyboard / stdin)
std::coutostreamstandard output (stdout)
std::cerrostreamstandard error, unbuffered
std::clogostreamstandard error, buffered
#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;            // read one int
    cout << "n = " << n << "\n";
    cerr << "debug\n";  // goes to stderr
}

Output with cout

#include <iostream>
#include <string>

std::cout << 42;                  // int
std::cout << 3.14;                // double
std::cout << "hello";             // string literal
std::cout << 'A';                 // char
std::cout << true;                // prints 1 (or "true" with boolalpha)
std::cout << x << " " << y;      // chaining
std::cout << "\n";                // newline (faster than endl)
std::cout << std::endl;           // newline + flush (use sparingly)
std::cout << std::flush;          // flush without newline

Input with cin

int a, b;
std::cin >> a >> b;               // reads two ints separated by whitespace

std::string word;
std::cin >> word;                 // reads one whitespace-delimited token

std::string line;
std::getline(std::cin, line);     // reads entire line including spaces

// After cin >>, discard leftover newline before getline:
std::cin >> a;
std::cin.ignore();                // discard one char (the '\n')
std::getline(std::cin, line);

// Or ignore up to '\n':
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Checking for read failure:

if (!(std::cin >> n)) {           // bad input
    std::cin.clear();             // reset error flags
    std::cin.ignore(1000, '\n'); // discard bad input
}

// Read until EOF:
int x;
while (std::cin >> x) { /* process x */ }

Format Manipulators (<iomanip>)

#include <iomanip>

// Width and alignment (applies to next output only)
std::cout << std::setw(10) << 42;           // "        42" (right-aligned)
std::cout << std::left << std::setw(10) << 42; // "42        "
std::cout << std::right << std::setw(10) << 42;
std::cout << std::setfill('0') << std::setw(5) << 7; // "00007"

// Floating-point precision
std::cout << std::fixed << std::setprecision(2) << 3.14159; // "3.14"
std::cout << std::scientific << std::setprecision(3) << 1234.5; // "1.235e+03"
std::cout << std::defaultfloat;             // restore default

// Number bases
std::cout << std::hex << 255;    // "ff"
std::cout << std::oct << 255;    // "377"
std::cout << std::dec << 255;    // "255" (default)
std::cout << std::uppercase << std::hex << 255; // "FF"
std::cout << std::showbase << std::hex << 255;  // "0xff"

// Booleans
std::cout << std::boolalpha << true;  // "true" instead of "1"
std::cout << std::noboolalpha;        // restore

// Show positive sign
std::cout << std::showpos << 42;      // "+42"
std::cout << std::noshowpos;

Sticky vs. non-sticky: setw resets after each item; all others are sticky until changed.

std::format (C++20)

#include <format>

std::string s = std::format("Hello, {}!", "world");
std::cout << s;

// Positional arguments
std::cout << std::format("{0} + {1} = {2}", 1, 2, 3);  // "1 + 2 = 3"

// Format specs: [[fill]align][sign][#][0][width][.precision][type]
std::cout << std::format("{:10}", 42);         // "        42"  (width 10)
std::cout << std::format("{:<10}", 42);        // "42        "  (left)
std::cout << std::format("{:>10}", 42);        // "        42"  (right)
std::cout << std::format("{:^10}", 42);        // "    42    "  (center)
std::cout << std::format("{:0>5}", 7);         // "00007"
std::cout << std::format("{:.2f}", 3.14159);   // "3.14"
std::cout << std::format("{:.3e}", 1234.5);    // "1.235e+03"
std::cout << std::format("{:x}", 255);         // "ff"
std::cout << std::format("{:#x}", 255);        // "0xff"
std::cout << std::format("{:b}", 10);          // "1010"
std::cout << std::format("{:+}", 42);          // "+42"

// Print directly (C++23)
// std::print("Hello, {}!\n", "world");

File I/O (<fstream>)

#include <fstream>
#include <string>

// Write to file
std::ofstream out("output.txt");
if (!out) { /* error opening */ }
out << "line 1\n" << 42 << "\n";
out.close();  // auto-called on destruction

// Append
std::ofstream app("output.txt", std::ios::app);
app << "appended line\n";

// Read from file
std::ifstream in("input.txt");
if (!in) { /* error */ }

int n;
in >> n;                // read formatted

std::string line;
while (std::getline(in, line)) {
    // process line
}

// Read entire file into string
std::string contents((std::istreambuf_iterator<char>(in)),
                      std::istreambuf_iterator<char>());

// Random access
in.seekg(0, std::ios::beg);   // seek to beginning
in.seekg(10);                  // seek to byte 10
auto pos = in.tellg();         // current position

Open modes (combine with |):

ModeMeaning
ios::inopen for reading
ios::outopen for writing (truncates)
ios::appappend, don't truncate
ios::trunctruncate on open
ios::binarybinary mode (no newline translation)
ios::ateseek to end after open
std::fstream rw("data.bin", std::ios::in | std::ios::out | std::ios::binary);

String Streams (<sstream>)

#include <sstream>

// Build a string using stream ops
std::ostringstream oss;
oss << "x=" << 42 << ", y=" << 3.14;
std::string result = oss.str();   // "x=42, y=3.14"

// Parse a string
std::istringstream iss("10 20 30");
int a, b, c;
iss >> a >> b >> c;   // a=10, b=20, c=30

// Round-trip: number → string
std::ostringstream ss;
ss << 255;
std::string hex_str = ss.str();

// Alternative: std::to_string / std::stoi (see Strings cheatsheet)

Stream State Flags

FlagMethod to checkMeaning
goodbits.good()no errors
eofbits.eof()end of file reached
failbits.fail()logical error (bad format)
badbits.bad()I/O error
if (std::cin.fail()) {
    std::cin.clear();                              // clear flags
    std::cin.ignore(1000, '\n');                  // discard bad input
}

// Common idiom: loop until valid int
int val;
while (!(std::cin >> val)) {
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cout << "Try again: ";
}

Binary I/O

#include <fstream>

struct Record { int id; double value; };
Record r{1, 3.14};

// Write binary
std::ofstream out("data.bin", std::ios::binary);
out.write(reinterpret_cast<const char*>(&r), sizeof(r));

// Read binary
std::ifstream in("data.bin", std::ios::binary);
Record r2;
in.read(reinterpret_cast<char*>(&r2), sizeof(r2));
auto bytes_read = in.gcount();  // actual bytes read

Performance Tips

// Untie cin from cout (remove automatic flush before reads)
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
// After this, don't mix C-style printf/scanf with C++ streams.

// Prefer "\n" over std::endl — endl flushes the buffer (slow in loops)
for (int i = 0; i < 1000; ++i)
    std::cout << i << "\n";   // fast

printf / scanf (C-style, <cstdio>)

#include <cstdio>

printf("%d %s %.2f\n", 42, "hello", 3.14);

// Common format specifiers
// %d / %i   int
// %u        unsigned int
// %ld       long
// %lld      long long
// %f        double (printf) / float (scanf)
// %lf       double (scanf)
// %e        scientific notation
// %g        shorter of f/e
// %s        const char*
// %c        char
// %x / %X   hex int
// %o        octal
// %p        pointer
// %%        literal %
// Width: %10d   Precision: %.3f   Left-align: %-10d   Zero-pad: %05d

int n;
scanf("%d", &n);     // read one int (address required)

char buf[256];
scanf("%255s", buf); // read word, limit to 255 chars
fgets(buf, 256, stdin); // read line including '\n'