Notifications

No notifications

/Phase 1

Input & Output Streams

Talking to the World 💬

C++ I/O is built on streams — think of them as conveyor belts of data. The two everyday stars:

  • std::cout — *console out* (your screen)
  • std::cin — *console in* (the keyboard / stdin)
#include <iostream>
using namespace std;

int main() { int age; cout << "Enter your age: "; cin >> age; cout << "You are " << age << " years old.\n"; }

The Stream Operators

OperatorReads asDirection
<<"put into"data → stream
>>"extract from"stream → variable

You can chain them — order matters, leftmost reads/writes first.

Reading Whole Lines

cin >> name stops at whitespace. To read an entire line use getline:

string fullName;
getline(cin, fullName);   // reads until newline

> ⚠️ Mixing cin >> with getline? The >> leaves the newline in the buffer; the next getline reads it as an empty line. Add cin.ignore(); between them.

Formatting Output

#include <iomanip>
cout << fixed << setprecision(2) << 3.14159;   // 3.14
cout << setw(8) << 42;                          // "      42"
cout << boolalpha << true;                       // "true" not "1"

Files? Same Streams

#include <fstream>
ofstream out("log.txt");
out << "saved!";

ifstream in("log.txt"); string s; in >> s;

Same << and >> work on files. That's the beauty of streams.

On this page

Detailed Theory

Streams are C++'s unified model for I/O. Once you learn cin/cout, the same syntax reads files, writes files, builds strings, and even talks over sockets in libraries.

The Stream Family

StreamHeaderJob
coutOutput to console
cinInput from console
cerrError output (unbuffered)
clogLogging (buffered)
ofstreamOutput to a file
ifstreamInput from a file
stringstreamRead/write to a string

They all share the same << / >> interface. Master one, master all.

Output: cout << ...

int x = 42;
double pi = 3.14;
string name = "Asha";

cout << "x=" << x << ", pi=" << pi << ", name=" << name << "\n";

Each << returns the stream, which is why you can chain.

Newlines: "\n" vs endl

cout << "fast\n";       // newline only — fast
cout << "slow" << endl; // newline + FLUSH (forces write to OS)

Inside loops or when you print millions of lines (competitive programming!), use "\n". Use endl only when you actually need a flush.

Input: cin >> ...

int a, b;
cin >> a >> b;          // reads two whitespace-separated numbers

>> skips leading whitespace, then reads tokens. It stops at the first whitespace (space, tab, newline).

Reading Strings — Two Modes

string word;
cin >> word;            // reads one word — stops at space

string line; getline(cin, line); // reads to end of line

The Classic Bug: >> Then getline

int n;
string line;
cin >> n;               // leaves '\n' in the buffer
getline(cin, line);     // ❌ reads empty string!

// FIX: cin >> n; cin.ignore(); // discard the leftover newline getline(cin, line); // ✅

cin.ignore(numeric_limits::max(), '\n') is the safer, full version.

Detecting End of Input

cin is "truthy" while it can still read.

int x;
while (cin >> x) {       // loops until EOF or read fails
    cout << x * 2 << "\n";
}

This pattern handles input streams of unknown length — perfect for files piped on stdin.

Formatted Output —

#include <iomanip>

cout << fixed << setprecision(3) << 1.0/3; // 0.333 cout << setw(10) << "hi"; // pads to width 10 (right-aligned) cout << left << setw(10) << "hi" << "

"; // left-aligned: "hi
" cout << setfill('0') << setw(4) << 42; // "0042" cout << hex << 255 << "\n"; // "ff" cout << boolalpha << true; // "true"

ManipulatorEffect
fixedFixed decimal notation
scientificScientific notation
setprecision(n)n digits after decimal (with fixed)
setw(n)Min field width n (one-shot)
setfill(c)Pad character
left / rightAlignment
hex / dec / octNumber base
boolalphaPrint true/false instead of 1/0

setw resets after one output; fixed, hex, etc. stay set until changed.

Files: ofstream & ifstream

#include <fstream>
#include <string>
using namespace std;

// Write ofstream out("data.txt"); out << "Hello\n" << 42 << "\n"; out.close(); // optional — destructor closes too

// Read ifstream in("data.txt"); string line; while (getline(in, line)) { cout << line << "\n"; }

Always check the file opened:

ifstream in("missing.txt");
if (!in) {
    cerr << "Could not open file\n";
    return 1;
}

Stringstream: Parse a String Like Input

#include <sstream>

string data = "42 3.14 hello"; stringstream ss(data);

int n; double d; string s; ss >> n >> d >> s; // n=42, d=3.14, s="hello"

Indispensable when you need to split a line into tokens.

Speed Tips (Competitive Programming)

By default, cin/cout synchronise with C's stdio — slower. To go fast:

ios_base::sync_with_stdio(false);
cin.tie(nullptr);

These two lines at the top of main can speed I/O up to 10x. After this, don't mix cin/cout with scanf/printf in the same program.

Cheat-Sheet

WantCode
Printcout << x;
Read intcin >> n;
Read linegetline(cin, s);
Read until EOFwhile (cin >> x) ...
2 decimal placescout << fixed << setprecision(2) << x;
Open file (read)ifstream in("a.txt");
Open file (write)ofstream out("a.txt");
Fast CP I/Oios::sync_with_stdio(false); cin.tie(nullptr);

I/O looks small, but it's where most beginner bugs hide. Master getline + cin.ignore() + while(cin >> x) and you've handled 90% of input formats you'll meet.