Beginner · First steps: compiling, output, variables and input · topic 4 of 42 · 25 min
Reading input and formatting output
Explanation
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.
#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";
}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.
int qty;
if (std::cin >> qty) {
std::cout << "OK: " << qty << '\n';
} else {
std::cout << "Please type a number\n";
}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.
#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';
}Formatting numbers with <iomanip>
#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
}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
#include <format>
#include <iostream>
int main() {
double fare = 1450.5;
std::cout << std::format("Fare: Rs {:.2f} for {} seats\n", fare, 3);
}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
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);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
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.
#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";
}Practice (0/4 done)
The user types: Asha Verma. What does std::string s; std::cin >> s; put in s?
What does this print? std::cout << std::fixed << std::setprecision(1) << 2.26 << " " << 3.0;
After std::cin >> age; the next std::getline(std::cin, city); gives an empty city. What is the fix?
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- std::optional, std::variant and std::string_viewModern C++: lambdas, C++17 and C++20 essentials
- Arrays, std::array and a first look at std::vectorReferences, pointers, arrays and strings
- C++20 ranges, views and other C++20 essentialsModern C++: lambdas, C++17 and C++20 essentials
- Text: C strings and std::stringReferences, pointers, arrays and strings
- Mini project: reading input from the userRust Programming · Types, control flow and functions
- std::map and std::unordered_mapThe Standard Template Library (STL)
Questions people ask about this
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.
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.
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.
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.
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
- This is the last topic of “First steps: compiling, output, variables and input”. The module exam comes next.
- Module 1 exam: First steps · 12 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, Decisions, loops and functions. 42 topics left in the course before the final exam.