C++ User Input

So far your programs only send data out with cout. To make them interactive, you need to read data in from the keyboard. In C++ this is done with cin, which reads what the user types and stores it in a variable.

Reading Input with cin

The object cin (short for character input) works as the opposite of cout. While cout uses the << operator to send data out, cin uses the >> operator to pull data in and place it into a variable.

Reading a number

#include <iostream>
using namespace std;

int main() {
  int age;
  cout << "Enter your age: ";
  cin >> age;
  cout << "You are " << age << " years old.";
  return 0;
}

You can read more than one value in a single statement by chaining several >> operators. The user separates their inputs with spaces or by pressing Enter between them.

Reading two numbers and adding them

#include <iostream>
using namespace std;

int main() {
  int a, b;
  cout << "Enter two numbers: ";
  cin >> a >> b;
  cout << "Sum: " << (a + b);
  return 0;
}

Reading a Full Line of Text

There is one catch with cin: when reading into a string, it stops at the first space. So typing "Mary Jane" would only store "Mary". To capture a whole line including spaces, use getline instead.

getline captures spaces

#include <iostream>
#include <string>
using namespace std;

int main() {
  string fullName;
  cout << "Enter your full name: ";
  getline(cin, fullName);
  cout << "Hello, " << fullName << "!";
  return 0;
}
Note: If you mix cin >> with getline, the leftover newline from the >> can be picked up by getline. A common fix is to call cin.ignore() before getline to discard that stray newline.
ToolBest for
cin >>Single words or numbers
getline(cin, s)A full line of text with spaces

Exercise: C++ User Input

Which object is used to read keyboard input in C++?