C++ ยท Chapter 8 of 49

C++ User Input

The `std::cin` object combined with the `>>` extraction operator reads input from the keyboard into a variable. It works with numbers, single words, and characters.

For reading a full line including spaces, use `std::getline(std::cin, variable)` instead of `cin >>`, since `>>` stops at whitespace.

Reading with cin

`cin >> variable;` waits for the user to type a value and Enter, then stores it into the variable, converting it to match the variable's type.

Reading full lines

Because `cin >>` stops at the first space, use `getline(cin, str)` when you need to capture an entire sentence into a std::string.

Example 1 (cpp)
int age;
std::cout << "Age: ";
std::cin >> age;
std::cout << "You are " << age;
Output
Age: 20
You are 20

cin >> reads a number typed by the user.

Example 2 (cpp)
std::string name;
std::getline(std::cin, name);
std::cout << "Hello " << name;
Output
Hello Ada Lovelace

getline captures the whole line, including spaces.

Key points

  • std::cin with >> reads typed input.
  • getline() reads an entire line including spaces.
  • Input is automatically converted to the variable's type.
  • Mixing cin >> and getline() needs care due to leftover newlines.
๐Ÿ’ก Note: If cin fails to convert input (e.g. letters into an int), the stream enters a fail state that must be cleared before further reads.

๐Ÿ“ Quick Quiz

1. Which operator reads input with cin?

2. Which function reads a full line with spaces?

3. cin >> stops reading at: