Skip to content

Beginner · First steps: compiling, output, variables and input · topic 4 of 42 · 25 min

Reading input and formatting output

Explanation

std::cin >> reads one word or number at a time, skipping spaces. std::getline reads a whole line, spaces included. You can format numbers with <iomanip> (fixed, setprecision, setw) or, in C++20, with std::format.

Reading with std::cin

std::cin is the "character input" stream: what the user types in the terminal. The >> operator reads from it into a variable. It skips spaces and newlines first, then reads one value that matches the variable's type.

cpp
#include <iostream>

int main() {
    int age;
    double height;
    std::cout << "Age and height: ";
    std::cin >> age >> height;
    std::cout << "You are " << age << " and " << height << " m tall\n";
}
Typing 21 1.68 and pressing Enter prints You are 21 and 1.68 m tall.

Checking that input worked

If the user types "abc" where a number is expected, the read fails: the variable gets 0 (since C++11) and cin goes into a fail state, after which every further read does nothing. You can test the stream like a bool.

cpp
int qty;
if (std::cin >> qty) {
    std::cout << "OK: " << qty << '\n';
} else {
    std::cout << "Please type a number\n";
}
std::cin >> qty is true when the read succeeded.

Whole lines: std::getline

>> stops at the first space, so reading the name "Asha Verma" with >> gives only "Asha". Use std::getline(std::cin, text) to read a full line into a std::string.

cpp
#include <iostream>
#include <string>

int main() {
    int roll;
    std::string fullName;
    std::cin >> roll;
    std::cin.ignore();                 // throw away the '\n' left after the number
    std::getline(std::cin, fullName);
    std::cout << roll << ": " << fullName << '\n';
}
Input 17 then Asha Verma prints 17: Asha Verma.
Careful: The famous getline bug: after std::cin >> roll, the Enter key's newline is still waiting in the input. getline then reads that empty line at once and your string is empty. Call std::cin.ignore() (or std::cin >> std::ws) before getline to skip it.
Think of it like this: Think of cin as a conveyor belt of characters at a sweet shop. >> picks up one sweet (one value) at a time and skips the paper between them. getline picks up the whole tray up to the end of the row. If a leftover paper (the newline) is on the belt, getline grabs that empty tray first.

Formatting numbers with <iomanip>

cpp
#include <iostream>
#include <iomanip>

int main() {
    double price = 1234.5;
    std::cout << std::fixed << std::setprecision(2) << price << '\n';   // 1234.50
    std::cout << std::setw(8) << 42 << "|\n";                           // "      42|"
    std::cout << std::boolalpha << true << '\n';                        // true
}
fixed + setprecision(2) gives exactly two decimal places. setw(8) pads the NEXT value to 8 characters.

Note that std::fixed and std::setprecision are "sticky": they stay in effect for all later output on that stream. setw applies only to the next value.

C++20: std::format

cpp
#include <format>
#include <iostream>

int main() {
    double fare = 1450.5;
    std::cout << std::format("Fare: Rs {:.2f} for {} seats\n", fare, 3);
}
Prints Fare: Rs 1450.50 for 3 seats. {} is replaced by the next argument; {:.2f} means two decimal places.

std::format is like Python's f-strings: a format string with {} placeholders. It needs a compiler with C++20 library support (GCC 13+, recent Clang with libc++, or Visual Studio 2019 16.10+). If <format> is missing on your compiler, use <iomanip>. C++23 adds std::print, which prints directly.

Fast input for big data

cpp
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
Put these two lines at the start of main when reading lakhs of numbers (common in contests). Do not mix printf/scanf with cin/cout after this.
Tip: Read the problem input format carefully. If a line has a name with spaces, you need getline; if it has numbers separated by spaces, >> is simplest.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Reading input and formatting output · 1/6

Input and output

Programs become useful when they read input. Let us read numbers, words and lines.

Prefer a video by a teacher? Find free videos on “c++ cin getline input output iomanip setprecision tutorial” on YouTube ↗

In real life: A school marks entry program

A teacher types each student's roll number, full name and marks. The program uses >> for the numbers and getline for the name (because names have spaces), then prints a neat report line with the percentage to two decimal places.

cpp
#include <iostream>
#include <iomanip>
#include <string>

int main() {
    int roll, marks;
    std::string name;
    std::cin >> roll >> std::ws;          // std::ws skips the leftover newline
    std::getline(std::cin, name);
    std::cin >> marks;
    double percent = marks * 100.0 / 500;
    std::cout << roll << " " << name << ": "
              << std::fixed << std::setprecision(2) << percent << "%\n";
}
Input 12 / Ravi Kumar / 437 prints 12 Ravi Kumar: 87.40%.

Practice (0/4 done)

Task 1 · Question

The user types: Asha Verma. What does std::string s; std::cin >> s; put in s?

Task 2 · Question

What does this print? std::cout << std::fixed << std::setprecision(1) << 2.26 << " " << 3.0;

Task 3 · Question

After std::cin >> age; the next std::getline(std::cin, city); gives an empty city. What is the fix?

Task 4 · Practice

Write a program that asks for an item name (may contain spaces), its price and quantity, and prints the bill total with exactly 2 decimal places. If the price is not a number, print an error message instead.

Quick quiz

Question 1

1.Which reads a whole line including spaces?

Question 2

2.What happens after std::cin >> n fails because the user typed "abc"?

Question 3

3.std::cout << std::setw(5) << 42; prints…

Question 4

4.What does std::format("{} + {} = {}", 2, 3, 5) give?

Question 5

5.Why add std::ios::sync_with_stdio(false); in contest code?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which reads a whole line including spaces?

Answer: std::getline(std::cin, line);

getline reads up to the newline, so spaces are kept.

What happens after std::cin >> n fails because the user typed "abc"?

Answer: cin enters a fail state and later reads do nothing until it is cleared

A failed read sets the fail state. Check the result, and use std::cin.clear() and ignore() to recover.

std::cout << std::setw(5) << 42; prints…

Answer: 42 (3 spaces then 42)

setw(5) pads the next value to 5 characters, on the left by default.

What does std::format("{} + {} = {}", 2, 3, 5) give?

Answer: "2 + 3 = 5"

Each {} is replaced by the next argument in order.

Why add std::ios::sync_with_stdio(false); in contest code?

Answer: To read faster when the input is very large

It unties C++ streams from C stdio, which makes cin/cout much faster. Do not mix printf/scanf with them afterwards.

What does std:: in std::cout mean?Related

Answer: cout comes from the std namespace

std is the namespace of the standard library and :: picks a name from it.

From Your first program: main, cout and namespaces

Why is std::string_view a good parameter type for read-only text?Related

Answer: It accepts std::string, literals and substrings without copying

A view is just a pointer and a length.

From std::optional, std::variant and std::string_view

What is the main advantage of std::vector over a C-style array?Related

Answer: Its size can change at run time and it knows its size

vector grows with push_back and reports size(); it also manages its own memory.

From Arrays, std::array and a first look at std::vector

What is std::span<const int> good for?Related

Answer: Passing any contiguous array (vector, std::array, C array) to a function without copying

span is a non-owning view of contiguous elements.

From C++20 ranges, views and other C++20 essentials

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. This is the last topic of “First steps: compiling, output, variables and input”. The module exam comes next.
  2. Module 1 exam: First steps · 12 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Decisions, loops and functions. 42 topics left in the course before the final exam.

← Previous: Variables, types and constants