C++ User Input (cin, getline)
std::cin reads what the user types. The input operator >> reads a value into a variable, and the variable's type decides what is read. In the editor, type your input in the terminal when the program waits, then press Enter.
Reading numbers and words
#include <iostream>
#include <string>
int main() {
std::string name;
int age;
std::cout << "What is your name? ";
std::cin >> name;
std::cout << "How old are you? ";
std::cin >> age;
std::cout << "Hello " << name << "! Next year you will be " << age + 1 << ".\n";
return 0;
}Asha 12
What is your name? How old are you? Hello Asha! Next year you will be 13.
Reading into a string stops at the first space, so cin >> name reads one word. Several values can be read in one statement: std::cin >> a >> b;.
Checking the input
If the user types letters where a number is expected, cin fails: the variable becomes 0 and further reads do nothing. Test the read itself: if (std::cin >> n) is true only when it worked.
#include <iostream>
int main() {
int n;
std::cout << "A whole number: ";
if (!(std::cin >> n)) {
std::cout << "That is not a whole number.\n";
return 1;
}
std::cout << "You typed " << n << ".\n";
return 0;
}abc
A whole number: That is not a whole number.
To try again after a failure, call std::cin.clear() to reset the error and std::cin.ignore(1000, '\n') to throw away the bad line.
Whole lines with getline
std::getline(std::cin, text) reads a whole line, spaces included.
#include <iostream>
#include <string>
int main() {
int age;
std::string city;
std::cout << "Age? ";
std::cin >> age;
std::cin.ignore(); // skip the Enter left after the number
std::cout << "City? ";
std::getline(std::cin, city);
std::cout << age << ", from " << city << "\n";
return 0;
}12 New Delhi
Age? City? 12, from New Delhi
The ignore() matters: after cin >> age, the Enter key is still waiting, and getline would read that empty rest of the line. Skip it first whenever you switch from >> to getline.
Reading until the end
while (std::cin >> n) keeps reading numbers until the input ends (Ctrl+D in the terminal) or something that is not a number is typed. It is the usual way to read a list of unknown length.
Practice exercises
- Read the length and width of a rectangle and print its area and perimeter.
- Read a full name with
getlineand print it with its number of characters. - Ask for a number again and again until the user types a valid one, using
clearandignore.