C++ User Input
So far our programs only produce output. To read what the user types you use std::cin ("character input") with the extraction operator >>. Think of the arrows as showing the direction the data flows: cout << value sends data out, cin >> variable pulls data in.
Note: The playgrounds on this site cannot type into a running program, so the examples that use
cinare shown as plain code. Copy them into your local compiler to try them. The runnable examples simulate input with fixed values or a string stream.
Reading a number
#include <iostream>
using namespace std;
int main() {
int age;
cout << "How old are you? ";
cin >> age;
cout << "Next year you will be " << age + 1 << "\n";
}A sample session in the terminal looks like this:
How old are you? 30
Next year you will be 31cin >> age skips any leading spaces, reads digits, converts them to an int and stores the result in age.
Reading several values
You can chain extractions. The user may separate the values with spaces, tabs or new lines:
int width, height;
cout << "Enter width and height: ";
cin >> width >> height;
cout << "Area: " << width * height << "\n";Reading a whole line
>> stops at the first whitespace, so reading "Ada Lovelace" into a string with cin >> name gives only "Ada". To read a full line, use std::getline:
#include <iostream>
#include <string>
using namespace std;
int main() {
string fullName;
cout << "Full name: ";
getline(cin, fullName);
cout << "Hello, " << fullName << "!\n";
}Tip: Mixing
cin >> xandgetlineis a classic trap:>>leaves the Enter key ('\n') in the buffer, so the nextgetlinereads an empty line. Callcin.ignore(numeric_limits<streamsize>::max(), '\n');(from<limits>) in between.
Simulating input with a string stream
A std::istringstream (from <sstream>) behaves exactly like cin, but reads from a string you provide. This is a great way to test input-handling code — and it runs right here:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
istringstream input("Ada Lovelace\n36 1.65\n");
string name;
int age;
double height;
getline(input, name);
input >> age >> height;
cout << "Name: " << name << "\n";
cout << "Age: " << age << "\n";
cout << "Height: " << height << "\n";
}Name: Ada Lovelace
Age: 36
Height: 1.65
Because cin and istringstream are both input streams, a function that takes std::istream& can read from either one. You will learn about references later in the course.
Checking for bad input
If the user types letters when a number is expected, the extraction fails: the variable is set to 0 and the stream enters a fail state. You can test the stream like a bool:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
istringstream input("abc"); // pretend the user typed "abc"
int n;
if (input >> n) {
cout << "You entered " << n << "\n";
} else {
cout << "That was not a number!\n";
}
}That was not a number!
With real input you would write if (cin >> n) in exactly the same way, then call cin.clear() to reset the error state before reading again.
Summary
| Task | Code |
|---|---|
| Read one word / number | cin >> x; |
| Read several values | cin >> a >> b; |
| Read a whole line | getline(cin, line); |
| Check success | if (cin >> x) { ... } |
| Reset after an error | cin.clear(); |
Test yourself
Which operator is used with cin?
- <<
- >>
- ->
- ::
The user types New York. What does cin >> city; store in a string city?
- New York
- New
- York
- Nothing
What happens when cin >> n (with int n) receives the text abc?
- n becomes 'a'
- The program crashes
- The stream enters a fail state
- n becomes 3