Reading Input with cin
cout sends values out to the screen. To read values in, use cin, which means "character input". The arrows show which way the data goes: << sends values out of the program, and >> brings values into a variable.
This program reads a name and an age. Here it gets the input Bob on the first line and 45 on the second:
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
int age;
cin >> name;
cin >> age;
cout << "Hi " << name << ", age " << age << "\n";
return 0;
}
Output:
Hi Bob, age 45
cin >> age reads the text 45 and turns it into the number 45, because age is an int. cin always converts the input to the type of the variable.
Here name and age have no starting value. That is fine when the very next lines give them a value with cin.
You can also read several values in one statement. With the input 10 20, this prints their sum:
int a, b;
cin >> a >> b;
cout << a + b << "\n";
Output:
30
cin >> reads one word
cin >> stops reading at a space or a new line. That is useful for reading values one by one. But it is a problem when one value has a space in it. Here is the first program again, with the name Mary Ann and the age 30:
string name;
int age;
cin >> name;
cin >> age;
cout << "Hi " << name << ", age " << age << "\n";
Output:
Hi Mary, age 0
name got only Mary. Then cin >> age tried to read Ann as a number. That failed, so age became 0. There was no error message. The output is simply wrong. If your input looks wrong, check whether the data has a space in it.
Read a whole line with getline
To read everything on a line, spaces included, use getline:
string city;
getline(cin, city);
cout << "[" << city << "]" << "\n";
Output:
[New York City]
Be careful when a getline comes after a cin >>. cin >> leaves the end of the line behind, and getline reads that empty rest of the line:
int age;
string city;
cin >> age;
getline(cin, city);
cout << "[" << city << "]" << "\n";
Output:
[]
The fix is cin.ignore(); between the two. It skips the leftover end of the line:
int age;
string city;
cin >> age;
cin.ignore();
getline(cin, city);
cout << "[" << city << "]" << "\n";
Output:
[New York City]
In the exercise, read a name and an age, and print a greeting.