Almost every useful program talks to the outside world. It reads some data (marks of a student, two numbers to add, a name), does some work, and then shows a result. Reading data is called input and showing results is called output.
In C, we used printf() and scanf(). C++ still allows them, but it gives us a more type-safe and more flexible system called I/O streams. In this chapter we will learn std::cout, std::cin, std::getline, formatting with <iomanip>, how to handle wrong input, and the modern C++23 way of printing with std::print and std::println.
What is a Stream?
A stream is a sequence of characters flowing from a source to a destination. An input stream brings characters into the program; an output stream carries characters out of the program.
Think of a stream like a water pipe. You don't care where the water comes from (keyboard, file, network). You just open the tap and characters come out one after another.
Keyboard ──► [ std::cin ] ──► your program
your program ──► [ std::cout ] ──► Screen
The header <iostream> gives us four ready-made stream objects:
| Object | Meaning | Connected to | Buffered? |
|---|---|---|---|
std::cin | Standard input | Keyboard (stdin) | Yes |
std::cout | Standard output | Screen (stdout) | Yes |
std::cerr | Standard error | Screen (stderr) | No — written immediately |
std::clog | Standard log | Screen (stderr) | Yes |
All of them live in the std namespace, which is why we write std::cout. (As discussed in C++ Program Structure, you may see using namespace std; in some code, but writing std:: is the safer habit.)
Output with std::cout
We send data to std::cout using the insertion operator <<. You can read it as "put into". The arrow points in the direction the data flows: from the value into the stream.
#include <iostream>
int main() {
int age = 20;
double cgpa = 8.75;
char grade = 'A';
std::cout << "Age: " << age << '\n';
std::cout << "CGPA: " << cgpa << ", Grade: " << grade << '\n';
std::cout << "Next year you will be " << age + 1 << std::endl;
return 0;
}
Output:
Age: 20
CGPA: 8.75, Grade: A
Next year you will be 21
Notice three things:
- No format specifiers. Unlike
printf("%d", age), we never tellcoutthe type. The compiler already knowsageis anintand picks the correct way to print it. This is why stream I/O is called type-safe: a mismatched%d/%fbug simply cannot happen. - Chaining.
std::cout << a << bworks becausestd::cout << areturnsstd::coutitself, so the next<< bis applied to the same stream. - Expressions are allowed.
age + 1is evaluated first and then printed.
Chaining works like this, step by step:
std::cout << "Age: " << age << '\n';
└──────┬──────────┘
returns std::cout
└───────── << age ──┘
returns std::cout
└──── << '\n'
'\n' vs std::endl
Both move the cursor to the next line, but they are not identical.
'\n' | std::endl |
|---|---|
| Inserts a newline character only | Inserts a newline and flushes the buffer |
| Fast | Slower if used inside large loops |
| Recommended for normal output | Use when output must appear immediately (for example, before a long computation) |
What is flushing? cout does not send every character to the screen immediately. It collects characters in a memory buffer and sends them in bigger chunks, because talking to the operating system is expensive. Flushing means "send whatever is in the buffer right now". Flushing after every line wastes time, so prefer '\n'.
Input with std::cin
We read data using the extraction operator >>, read as "take out of". Again, the arrow shows the flow: from the stream into the variable.
#include <iostream>
int main() {
int a, b;
std::cout << "Enter two numbers: ";
std::cin >> a >> b;
std::cout << "Sum = " << a + b << '\n';
return 0;
}
Sample run (the user types 12 30 and presses Enter):
Enter two numbers: 12 30
Sum = 42
How does >> work for numbers?
- It skips leading whitespace (spaces, tabs, newlines).
- It reads characters as long as they can form a valid number.
- It stops at the first character that cannot belong to the number and leaves that character in the stream for the next read.
Because whitespace is skipped, the user could also type 12, press Enter twice, and then type 30. The result would still be Sum = 42.
You may wonder why the prompt Enter two numbers: appears before the program waits, even though it has no '\n' and nothing flushed it. The reason: std::cin is tied to std::cout. Before cin reads anything, it automatically flushes cout. So prompts always show up in time.
Reading a String with >>
For a std::string, >> reads one word: it skips leading whitespace and stops at the next whitespace.
#include <iostream>
#include <string>
int main() {
std::string word;
std::cout << "Enter your full name: ";
std::cin >> word;
std::cout << "You typed: [" << word << "]\n";
return 0;
}
Sample run:
Enter your full name: Rahul Kumar Sharma
You typed: [Rahul]
Only Rahul was read. Kumar Sharma is still waiting in the input stream.
Reading a Whole Line with std::getline
To read a complete line including spaces, use std::getline(stream, stringVariable) from <string>. It reads characters until it finds '\n', removes that newline from the stream, and does not store it in the string.
#include <iostream>
#include <string>
int main() {
std::string name;
std::cout << "Enter your full name: ";
std::getline(std::cin, name);
std::cout << "Hello, " << name << "!\n";
return 0;
}
Sample run:
Enter your full name: Rahul Kumar Sharma
Hello, Rahul Kumar Sharma!
The Classic Trap: cin >> followed by getline
This is one of the most common beginner bugs in C++, and a favourite interview question.
#include <iostream>
#include <string>
int main() {
int roll;
std::string name;
std::cout << "Roll number: ";
std::cin >> roll;
std::cout << "Name: ";
std::getline(std::cin, name); // Problem!
std::cout << "Roll = " << roll << ", Name = [" << name << "]\n";
return 0;
}
Sample run (user types 42 and presses Enter; the program does not even wait for the name):
Roll number: 42
Name: Roll = 42, Name = []
Why? Let's look at what is inside the input stream after the user types 42 and presses Enter:
Input buffer: 4 2 \n
└─┬──┘ │
cin >> roll reads 42 └── left behind!
getline sees '\n' immediately → reads an empty line → done.
>> stops before the newline. Then getline finds that leftover newline first, decides the line is empty, and returns at once.
Fix: throw away the leftover whitespace before calling getline. The cleanest way is the std::ws manipulator, which skips all whitespace:
std::getline(std::cin >> std::ws, name); // skip leftover whitespace first
Sample run with the fix:
Roll number: 42
Name: Priya Singh
Roll = 42, Name = [Priya Singh]
Another common fix is std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); right after cin >> roll. It discards everything up to and including the next newline. (std::numeric_limits needs <limits>.) The difference: std::ws also skips leading spaces of the name, while ignore keeps them.
Reading Single Characters
cin >> ch for a char also skips whitespace. If you want to read every character, including spaces and newlines, use cin.get(ch).
#include <iostream>
int main() {
char c1, c2, c3;
std::cin >> c1 >> c2; // >> skips spaces
std::cin.get(c3); // get() does not skip anything
std::cout << "[" << c1 << "][" << c2 << "][" << c3 << "]\n";
return 0;
}
Input: a b c
Output:
[a][b][ ]
c3 got the space character that comes after b, not the letter c.
When the User Types Something Wrong
What happens if the program expects an int and the user types ninety? The extraction fails. Three things happen:
- The stream sets its failbit. The stream is now in a "failed" state, and
if (!std::cin)becomes true. - Since C++11, the target variable is set to
0(or to the maximum/minimum value if the number was too large/small for the type). - The bad characters stay in the stream. Every further
>>fails immediately until we repair the stream.
Repairing takes two steps: clear() the error flags, then ignore() the bad input.
#include <iostream>
#include <limits>
int main() {
int marks;
std::cout << "Enter marks: ";
std::cin >> marks;
if (!std::cin) {
std::cout << "That was not a number! marks = " << marks << '\n';
std::cin.clear(); // 1. reset the error flags
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // 2. throw away the bad line
std::cout << "Enter marks again: ";
std::cin >> marks;
}
std::cout << "Marks = " << marks << '\n';
return 0;
}
Sample run:
Enter marks: ninety
That was not a number! marks = 0
Enter marks again: 90
Marks = 90
The order matters: ignore() does nothing on a failed stream, so clear() must come first. (This program uses if, which we cover properly in Conditional Statements.)
Reading Until the Input Ends
Because a stream converts to false when a read fails, a very common pattern is to keep reading while reads succeed. This uses a while loop, which we will study in the Loops chapter; for now just notice the idea.
#include <iostream>
int main() {
int x, sum = 0, count = 0;
while (std::cin >> x) { // stops at end of input or on a non-number
sum += x;
++count;
}
std::cout << "Read " << count << " numbers, sum = " << sum << '\n';
return 0;
}
Input:
10 20
30
40 50
Output:
Read 5 numbers, sum = 150
When typing on a keyboard, you signal "end of input" with Ctrl+D (Linux/macOS) or Ctrl+Z then Enter (Windows).
Formatting Output with <iomanip>
Manipulators are special values you insert into a stream to change how the following values are printed. Some are in <iostream> (std::fixed, std::left, std::boolalpha, std::hex), and those that take an argument (std::setw, std::setprecision, std::setfill) need <iomanip>.
#include <iostream>
#include <iomanip>
int main() {
double pi = 3.14159265;
std::cout << pi << '\n'; // default: 6 significant digits
std::cout << std::setprecision(3) << pi << '\n'; // 3 significant digits
std::cout << std::fixed << std::setprecision(2) << pi << '\n'; // 2 digits after the point
std::cout << 10.0 << '\n'; // fixed is sticky!
std::cout << '[' << std::setw(6) << 42 << "]\n"; // right-aligned in width 6
std::cout << '[' << std::left << std::setw(6) << 42 << "]\n";
std::cout << '[' << std::right << std::setfill('0') << std::setw(6) << 42 << "]\n";
std::cout << std::boolalpha << (5 > 3) << ' ' << std::noboolalpha << (5 > 3) << '\n';
std::cout << std::hex << std::showbase << 255 << ' ' << std::oct << 8 << std::dec << '\n';
return 0;
}
Output:
3.14159
3.14
3.14
10.00
[ 42]
[42 ]
[000042]
true 1
0xff 010
The table below summarises the most useful manipulators. The most important column is the last one: most manipulators are sticky (they stay in effect until changed), but setw applies only to the next value.
| Manipulator | Effect | Lasts for |
|---|---|---|
std::setw(n) | Minimum field width n | Next value only |
std::setprecision(n) | n significant digits (or digits after the point with fixed) | Sticky |
std::fixed | Fixed-point notation (3.14) | Sticky |
std::scientific | Scientific notation (3.14e+00) | Sticky |
std::left / std::right | Alignment inside the width | Sticky |
std::setfill(c) | Padding character | Sticky |
std::boolalpha | Print true/false instead of 1/0 | Sticky |
std::hex / std::oct / std::dec | Number base for integers | Sticky |
std::showbase | Show 0x / 0 prefix | Sticky |
Worked Example: A Neat Marks Table
#include <iostream>
#include <iomanip>
#include <string>
int main() {
std::string names[] = {"Aman", "Sneha", "Mohammed"};
double marks[] = {78.5, 91.4, 66};
std::cout << std::left << std::setw(10) << "Name"
<< std::right << std::setw(8) << "Marks" << '\n';
std::cout << std::fixed << std::setprecision(1);
std::cout << std::left << std::setw(10) << names[0] << std::right << std::setw(8) << marks[0] << '\n';
std::cout << std::left << std::setw(10) << names[1] << std::right << std::setw(8) << marks[1] << '\n';
std::cout << std::left << std::setw(10) << names[2] << std::right << std::setw(8) << marks[2] << '\n';
return 0;
}
Output:
Name Marks
Aman 78.5
Sneha 91.4
Mohammed 66.0
We used setw again before every value because it resets after each use. Arrays like names[] are covered in the Arrays chapter; here they just save typing.
Modern Printing: std::print and std::println (C++23)
Manipulators are powerful but wordy. C++20 added std::format (header <format>), which builds a string from a format string with {} placeholders, similar to Python. C++23 added std::print and std::println (header <print>), which format and print in one step. println adds a newline at the end; print does not.
#include <print>
#include <string>
int main() {
std::string name = "Sneha";
int rank = 7;
double score = 91.256;
std::println("Hello, {}!", name);
std::println("Rank {} with score {:.2f}", rank, score);
std::println("[{:>6}] [{:<6}] [{:^6}] [{:06}]", rank, rank, rank, rank);
std::println("hex: {:#x}, binary: {:b}", 255, 5);
std::print("no newline here, ");
std::print("so this continues\n");
return 0;
}
Output:
Hello, Sneha!
Rank 7 with score 91.26
[ 7] [7 ] [ 7 ] [000007]
hex: 0xff, binary: 101
no newline here, so this continues
Inside the braces, after a colon, you write a format spec: > right-align, < left-align, ^ centre, a number for width, .2f for two digits after the decimal point, x/b for hexadecimal/binary, and # to show the prefix. The format string is checked at compile time, so a wrong spec like {:d} for a string is a compile error rather than a runtime surprise.
This needs a recent compiler with -std=c++23 (for example GCC 14 or newer, or a recent Clang or MSVC). If your compiler or online judge is older, use std::cout; everything else in this tutorial works with it.
std::cerr and std::clog
Error messages should go to std::cerr, not std::cout. Both usually appear on the same screen, but the operating system treats them as two separate channels, so a user can redirect normal output to a file while still seeing errors.
#include <iostream>
int main() {
std::cout << "Normal output\n";
std::cerr << "Error: file not found\n";
std::clog << "Log: program finished\n";
return 0;
}
Output on the terminal:
Normal output
Error: file not found
Log: program finished
If we run it as ./a.out 2>/dev/null (which discards the error channel), only Normal output is shown. cerr is unbuffered, so an error message appears even if the program crashes right after printing it.
cin/cout vs scanf/printf
| Point | cin / cout | scanf / printf |
|---|---|---|
| Header | <iostream> | <cstdio> |
| Type safety | Type is deduced automatically | Programmer must match %d, %f... (mismatch is undefined behavior) |
| Address operator for input | Not needed: cin >> x | Needed: scanf("%d", &x) |
| User-defined types | Can be extended with operator overloading | Not possible |
| Formatting | Manipulators, or std::format/std::print | Format string |
| Speed | Slightly slower by default; fast after the two lines below | Fast |
In competitive programming you often see these two lines at the start of main:
std::ios::sync_with_stdio(false); // stop syncing C++ streams with C stdio
std::cin.tie(nullptr); // don't flush cout before every cin read
They make cin/cout about as fast as scanf/printf. After using them, do not mix printf with cout (or scanf with cin) in the same program, because the output order is no longer guaranteed. Also remember that without the tie, prompts are not flushed automatically. We discuss this more in C++ for Competitive Programming.
Common Mistakes
1. Arrows in the Wrong Direction
std::cin << x; // Error: cin uses >>
std::cout >> x; // Error: cout uses <<
Remember: data flows in the direction of the arrows. cout << x pushes x out; cin >> x pulls data into x.
2. Expecting cin >> to Read Spaces
cin >> name reads one word. Use std::getline for full lines.
3. Mixing cin >> and getline Without Removing the Newline
Use std::getline(std::cin >> std::ws, line) or cin.ignore(...).
4. Forgetting That a Failed Stream Stays Failed
After a bad input, every later >> fails silently. Always clear() and then ignore().
5. Forgetting That Manipulators Are Sticky
After std::fixed << std::setprecision(2), every later double prints with two decimals. Only setw resets itself.
6. Using std::endl Everywhere
It flushes every time. In a loop that prints a million lines, this can make the program many times slower. Use '\n'.
Interview / Exam Questions
What is the difference between '\n' and std::endl?
Both end the line. std::endl additionally flushes the output buffer, which forces a system call. '\n' only inserts the newline character, so it is faster.
Why can we write std::cout << a << b << c?
The expression std::cout << a returns a reference to std::cout itself. The next << b is then applied to that same stream, and so on. This is called chaining.
Input is 25 then Enter then Ravi Kumar. The code is cin >> age; getline(cin, name);. What is name?
An empty string. cin >> age leaves the newline in the buffer, and getline reads up to that newline immediately. Fix it with getline(cin >> ws, name).
Which of cout, cerr, clog is unbuffered?
std::cerr. Output sent to it is flushed after every operation. std::clog also writes to the error channel but is buffered.
What does std::cout << std::setw(5) << 7 << 8; print?
78 (four spaces, then 7, then 8). The width 5 applies only to 7; 8 is printed with no padding.
What value does an int get if cin >> x fails because the user typed letters?
Since C++11, it is set to 0 and the stream's failbit is set. (If the number is too large or too small, the variable gets the maximum or minimum value of the type instead.)
Which C++ standard introduced std::print and std::println?
C++23, in the header <print>. The formatting library they use, std::format, came in C++20.
In Simple Words
std::cout <<sends data out,std::cin >>brings data in, and the types are handled for you.
std::cout << x → print x
std::cin >> x → read one value (skips whitespace)
std::getline(cin, s) → read a whole line
'\n' → newline (prefer this)
std::endl → newline + flush
setw / setprecision → format output (<iomanip>)
std::println("{}", x) → C++23 formatted printing (<print>)
Now that our programs can read and print values, let's learn how to compute with them using operators.