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.
int age;
std::cout << "Age: ";
std::cin >> age;
std::cout << "You are " << age;Age: 20
You are 20cin >> reads a number typed by the user.
std::string name;
std::getline(std::cin, name);
std::cout << "Hello " << name;Hello Ada Lovelacegetline 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.
