Introduction & Syntax
Input/Output with cin and cout · Study material
Input and output in C++ is done with streams: std::cout sends data to the screen with the insertion operator <<, and std::cin reads from the keyboard with the extraction operator >>. Behind those two operators is a complete system – manipulators that format numbers and tables, getline for whole lines, stream states that tell you when input was wrong, string streams for parsing, and, since C++20/23, std::format and std::print. Questions like "why does getline skip my input?" or "what does setw(5) apply to?" are asked in every C++ exam and interview. This page explains all of it with programs you can run, followed by 60 practice questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – verified on a real C++ compiler.
On this page
- Streams: cin, cout, cerr and clog, insertion and extraction
- Formatting with manipulators: setw, setfill, setprecision, fixed, hex …
- Reading input: >>, getline, the leftover-newline trap and std::ws
- Stream states, input validation, reading until end of input
- Character I/O, string streams, std::format, std::print and fast I/O
What is a stream?
A stream is a sequence of characters flowing between your program and a device. <iostream> provides four ready-made stream objects:
| Object | Type | Connected to | Buffered |
|---|---|---|---|
std::cin | std::istream | standard input (keyboard) | yes |
std::cout | std::ostream | standard output (screen) | yes |
std::cerr | std::ostream | standard error | no – appears immediately |
std::clog | std::ostream | standard error | yes – for logs |
<< and >> are overloaded operators that return the stream itself, which is why they can be chained: std::cout << a << b is (std::cout << a) << b. Since C++17 the operands of a chain are evaluated left to right.
#include <iostream>
#include <string>
int main() {
std::string course = "C++";
int lessons = 24;
double rating = 4.8;
std::cout << course << " has " << lessons << " lessons, rated " << rating << '\n';
std::cout << "Characters: " << 'A' << ' ' << static_cast<char>(66) << '\n';
std::cerr << "This goes to the error stream\n"; // not part of normal output
return 0;
}
C++ has 24 lessons, rated 4.8 Characters: A B
Formatting output with manipulators
Manipulators are inserted into a stream to change how the next values are written. Those taking arguments live in <iomanip>. Most are sticky – they stay in effect until changed – but std::setw applies only to the next value.
| Manipulator | Effect | Lasts |
|---|---|---|
std::setw(n) | minimum width of the next field | next value only |
std::setfill(c) | padding character | sticky |
std::left / std::right | alignment inside the width | sticky |
std::setprecision(n) | significant digits, or decimals with fixed/scientific | sticky |
std::fixed / std::scientific / std::defaultfloat | floating-point notation | sticky |
std::hex / std::oct / std::dec | integer base | sticky |
std::showbase, std::uppercase, std::showpos | 0x prefix, capital letters, + sign | sticky |
std::boolalpha | true/false instead of 1/0 | sticky |
std::endl / std::flush | newline + flush / flush only | – |
#include <iomanip>
#include <iostream>
int main() {
std::cout << std::left << std::setw(10) << "Item" << std::right << std::setw(6) << "Qty"
<< std::setw(10) << "Price" << '\n';
std::cout << std::setfill('-') << std::setw(26) << "" << std::setfill(' ') << '\n';
std::cout << std::fixed << std::setprecision(2);
std::cout << std::left << std::setw(10) << "Pen" << std::right << std::setw(6) << 12 << std::setw(10) << 10.5 << '\n';
std::cout << std::left << std::setw(10) << "Notebook" << std::right << std::setw(6) << 3 << std::setw(10) << 45.0 << '\n';
return 0;
}
Item Qty Price -------------------------- Pen 12 10.50 Notebook 3 45.00
#include <iomanip>
#include <iostream>
int main() {
double v = 1234.5678;
std::cout << v << " | " << std::setprecision(3) << v << '\n'; // significant digits
std::cout << std::fixed << v << " | " << std::scientific << v << '\n'; // digits after the point
std::cout << std::defaultfloat << std::setprecision(6);
int n = 255;
std::cout << std::hex << n << ' ' << std::showbase << n << ' ' << std::uppercase << n << '\n';
std::cout << std::oct << n << ' ' << std::dec << std::noshowbase << n << '\n';
std::cout << std::showpos << 42 << ' ' << -42 << std::noshowpos << ' ' << std::boolalpha << true << '\n';
return 0;
}
1234.57 | 1.23e+03 1234.568 | 1.235e+03 ff 0xff 0XFF 0377 255 +42 -42 true
Reading input with std::cin and >>
std::cin >> x skips leading whitespace (spaces, tabs, newlines), then reads characters that fit x's type and stops at the first one that does not. For a std::string it reads one word; for a char it reads one non-space character. Values may be spread over several lines.
#include <iostream>
#include <string>
int main() {
int roll;
std::string first_name;
double cgpa;
char section;
std::cin >> roll >> first_name >> cgpa >> section; // whitespace and newlines are skipped
std::cout << "Roll " << roll << ": " << first_name << ", CGPA " << cgpa << ", section " << section << '\n';
return 0;
}
17 Kavya 8.9 B
Roll 17: Kavya, CGPA 8.9, section B
Reading whole lines with std::getline
std::getline(std::cin, s) reads everything up to the newline (which it removes), spaces included. The classic trap: after std::cin >> age the newline is still waiting, so the next getline returns an empty string at once. Skip it with std::cin >> std::ws (all whitespace) or std::cin.ignore() (one character). A third argument changes the delimiter: std::getline(in, field, ',').
#include <iostream>
#include <string>
int main() {
int age;
std::string full_name, city;
std::cin >> age; // leaves the '\n' after 21 in the input
std::getline(std::cin >> std::ws, full_name); // std::ws skips that newline (and spaces)
std::getline(std::cin, city); // reads the whole next line, spaces included
std::cout << '[' << full_name << "] " << age << " from [" << city << "]\n";
return 0;
}
21 Rahul Kumar Sharma New Delhi
[Rahul Kumar Sharma] 21 from [New Delhi]
Stream states and input validation
Every stream has state flags. A failed extraction (letters where a number was expected) sets failbit; since C++11 the variable is set to 0. While the stream is in a fail state every further read does nothing, so you must call clear() and discard the bad input with ignore().
| Function | True when |
|---|---|
good() | no error flag is set |
fail() | the last operation failed (failbit or badbit) |
eof() | end of input was reached |
bad() | an unrecoverable stream error occurred |
if (std::cin) / !std::cin | same as !fail() / fail() |
#include <iostream>
#include <limits>
int main() {
int value;
while (true) {
std::cout << "Enter a number: ";
if (std::cin >> value) break; // success
if (std::cin.eof()) return 1; // no more input
std::cout << "not a number\n";
std::cin.clear(); // reset the fail state
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // discard the bad line
}
std::cout << "\ngot " << value << '\n';
return 0;
}
hello abc 42
Enter a number: not a number Enter a number: not a number Enter a number: got 42
Reading until the end of input
Because std::cin >> x returns the stream, and a stream converts to false when it has failed, while (std::cin >> x) reads values until the input ends (Ctrl+D on Linux/macOS, Ctrl+Z then Enter on Windows) or a value does not match. This is the standard loop in competitive programming.
#include <iostream>
int main() {
long long sum = 0;
int count = 0, x;
while (std::cin >> x) { // false at end of input or on a non-number
sum += x;
++count;
}
std::cout << count << " numbers, sum " << sum << '\n';
return 0;
}
10 20 30 40 50 81
6 numbers, sum 231
Character input: get, peek, ignore, putback
std::cin.get(c) reads the next character including whitespace; peek() looks at it without removing it; ignore(n, delim) discards characters; putback(c) returns one. Output has put(c) and write(ptr, n).
#include <cctype>
#include <iostream>
int main() {
char c;
int letters = 0, digits = 0, spaces = 0;
while (std::cin.get(c)) { // get() does NOT skip whitespace
if (std::isalpha(static_cast<unsigned char>(c))) ++letters;
else if (std::isdigit(static_cast<unsigned char>(c))) ++digits;
else if (c == ' ' || c == '\n') ++spaces;
}
std::cout << letters << " letters, " << digits << " digits, " << spaces << " spaces/newlines\n";
return 0;
}
Room 101 Floor 2 Block C
15 letters, 4 digits, 6 spaces/newlines
String streams: parsing and building strings
std::istringstream (in <sstream>) reads from a string exactly like cin reads from the keyboard; std::ostringstream collects output into a string you get back with str(). They are the safest way to parse lines and to build text with manipulators. std::quoted (in <iomanip>) writes and reads strings with quotes and escapes.
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::istringstream in("Asha 91 Ravi 78 Meera 85"); // read from a string like from cin
std::string name;
int marks, total = 0;
while (in >> name >> marks)
total += marks;
std::ostringstream out; // write into a string like to cout
out << "total=" << total << ", average=" << std::fixed << std::setprecision(1) << total / 3.0;
std::string report = out.str();
std::cout << report << " (" << report.size() << " chars)\n";
std::cout << std::quoted("He said \"done\"") << '\n'; // quotes and escapes a string
return 0;
}
total=254, average=84.7 (23 chars) "He said \"done\""
Modern output: std::format and std::print
std::format (C++20, <format>) builds a string from a format string with {} placeholders; C++23 std::print and std::println (<print>) write it directly. Format specs follow the colon: {:<10} left-align in 10, {:>8.2f} right-align with 2 decimals, {:#x} hex with 0x, {{ a literal brace. Wrong argument types are compile errors.
#include <format>
#include <print>
int main() {
std::println("{:<8}{:>8}{:>10}", "City", "Temp", "Rain(mm)");
std::println("{:<8}{:>8.1f}{:>10}", "Chennai", 31.46, 12);
std::println("{:<8}{:>8.1f}{:>10}", "Shimla", 8.0, 140);
std::print("{} + {} = {}\n", 2, 3, 2 + 3);
std::println("Braces: {{}} and {:#x} {:08.3f}", 255, 3.14159);
return 0;
}
City Temp Rain(mm)
Chennai 31.5 12
Shimla 8.0 140
2 + 3 = 5
Braces: {} and 0xff 0003.142Fast input/output
By default C++ streams are synchronised with C's printf/scanf, and cin flushes cout before every read. For programs reading millions of numbers, two lines at the start of main make iostreams as fast as C I/O – but afterwards do not mix cin/cout with scanf/printf.
#include <iostream>
int main() {
std::ios::sync_with_stdio(false); // stop syncing with C stdio – big speed-up
std::cin.tie(nullptr); // don't flush cout before every cin read
int n;
std::cin >> n;
long long sum = 0;
for (int i = 0, x; i < n; ++i) {
std::cin >> x;
sum += x;
}
std::cout << sum << '\n'; // '\n', not std::endl
}
Common mistakes
- getline after >> returns an empty line – use
std::cin >> std::wsfirst. - Not checking reads: after bad input the stream fails silently and loops forever – test
if (std::cin >> x). - Expecting setw to stay: it applies to one value only.
- Forgetting fixed:
setprecision(2)alone means 2 significant digits. - Leaving hex on:
std::hexstays untilstd::dec. - std::endl in loops: flushing every line is slow – use
'\n'.
Key points to remember
- cout << writes, cin >> reads; both return the stream so they chain.
- >> skips whitespace and reads one word; getline reads a whole line.
- setw lasts for one value; other manipulators are sticky.
- Check every read; clear() and ignore() recover from bad input.
- Use string streams to parse lines and std::format / std::print for modern formatting.
Frequently asked questions
Why does getline not wait for input?
A previous cin >> left the newline in the buffer, and getline reads that empty line. Use std::getline(std::cin >> std::ws, line).
Is cout slower than printf?
With default settings it can be, mostly because of synchronisation and flushing. With std::ios::sync_with_stdio(false), std::cin.tie(nullptr) and '\n' instead of endl it is as fast. std::print is faster still.
How do I read a whole line with spaces?
Use std::getline(std::cin, s); std::cin >> s stops at the first space.
Where can I learn more?
Read Fast I/O in C++ and C++ std::string, then practise with the exercises below.