Show contents
Chapter 2 of 6 · 15 min
Reading the keyboard with std::cin
By the end of this chapter, you'll be able to
- Read numbers and words with std::cin and the >> operator
- Read a whole line, spaces included, with std::getline
- Detect invalid input and react cleanly
- Avoid the line-break trap between >> and getline
Reading with >>
std::cin ("character input") represents standard input, the keyboard. The >> operator extracts a value from it and stores it in a variable, converting it according to the variable's type:
#include <iostream>
int main() {
int age = 0;
std::cout << "Your age: ";
if (!(std::cin >> age)) {
std::cout << "That's not a number.\n";
return 1;
}
std::cout << "In 5 years, you'll be " << age + 5 << ".\n";
return 0;
}
If the user types 19 then Enter:
19
Your age: In 5 years, you'll be 24.
(In a real terminal, what you type appears after the question, and the answer comes on the next line.)
The expression std::cin >> age is "true" if reading succeeded. If the user types hello, the conversion to int fails: std::cin goes into a failure state, and every following read will fail too. The ! in front tests exactly that failure. The return 1; ends the program and signals an error.
>> skips spaces and line breaks, then reads up to the next space. You can chain several reads:
#include <iostream>
#include <string>
int main() {
std::string product;
int quantity = 0;
double price = 0;
if (std::cin >> product >> quantity >> price) {
std::cout << quantity << " x " << product << " = " << quantity * price << "\n";
}
return 0;
}
mangoes 4 0.75
4 x mangoes = 3
Reading a whole line
To read a text that contains spaces, like a full name or an address, >> isn't enough: it stops at the first space. std::getline reads the whole line, up to the Enter key:
#include <iostream>
#include <string>
int main() {
std::string name;
std::cout << "Full name: ";
std::getline(std::cin, name);
std::cout << "\nWelcome, " << name << " (" << name.size() << " characters)\n";
return 0;
}
Lucas Ferreira
Full name:
Welcome, Lucas Ferreira (14 characters)
name.size() returns the length of the text. As in C, it counts bytes: an accented letter counts as two.
getline then reads the right line.
Text description of the animation
- The user types 25, Enter, then Amina Diallo, Enter. Everything waits in the buffer, including both line breaks.
- >> reads 25 and stops just before the line break, which it leaves in the buffer.
- getline reads up to the next \n… which is the very first character. It returns an empty line.
- The fix: before getline, std::ws swallows the waiting spaces and line breaks.
- getline then reads the right line.
Your turn
Worked exercise
Worked exercise: the calculator
Write a program that reads an operation in the form number operator number (for example 12 * 4) and displays the result. The possible operators are +, -, * and /. The program must refuse invalid input, an unknown operator and division by zero.
Hint 1
char: std::cin >> a >> op >> b.Hint 2
switch on op handles the four cases. The / case first checks that b isn't zero.Show the solution and common mistakes
#include <iostream>
int main() {
double a = 0, b = 0;
char op = ' ';
if (!(std::cin >> a >> op >> b)) {
std::cout << "Invalid input\n";
return 1;
}
switch (op) {
case '+': std::cout << a + b << "\n"; break;
case '-': std::cout << a - b << "\n"; break;
case '*': std::cout << a * b << "\n"; break;
case '/':
if (b == 0) {
std::cout << "Can't divide by zero\n";
return 1;
}
std::cout << a / b << "\n";
break;
default:
std::cout << "Unknown operator: " << op << "\n";
return 1;
}
return 0;
}
12 * 4
48
Common mistakes:
- Reading
opinto astd::string: with12 *4,>>would read*4in one go. Acharreads exactly one character. - Forgetting the division-by-zero case: with
doubles,12 / 0doesn't crash, but displaysinf, which means nothing to the user.
Summary
- 1std::cin >> variable reads a value and converts it according to the variable's type.
- 2if (!(std::cin >> x)) detects invalid input: always check your reads.
- 3>> stops at the first space; std::getline reads a whole line.
- 4Before a getline that follows a >>, write std::cin >> std::ws to skip the line break.
- 5Invalid input is reported with a message and return 1.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.