C++ User Input
Lesson outline
Introduction to User Input
While output is useful for displaying results, most programs also need to receive input from users to be interactive.
In C++, the std::cin object together with the extraction operator (>>) is used to read from the program's standard input (typically the keyboard).
User input makes programs dynamic, producing different results depending on what the user provides.
Basic Input Example
This example reads an integer from the user:
Input Mechanics
The std::cin object (pronounced "see-in") works with the extraction operator (>>) to:
- Pause program execution until input is available
- Parse and convert the input to the variable's type
- Handle different input types (numbers, characters, etc.)
If the input cannot be parsed as the requested type, the stream sets failbit, stops further formatted extraction, and the target variable is left unchanged.
Multiple Input Values
You can read multiple values in a single line or separated by spaces:
Building a Simple Calculator
Here's a simple calculator that adds two numbers entered by the user:
Mixing >> and std::getline
When mixing formatted extraction (>>) with std::getline(), the trailing newline left in the buffer can cause std::getline() to read an empty line. Discard the remainder of the current line first:
Input Best Practices
To make programs more user-friendly and reliable:
- Always provide clear prompts so users know what to enter
- Use the correct variable type for expected input
- Consider adding input validation
- Handle errors gracefully
- Use
std::getline()for string input if spaces are expected
Common Input Pitfalls
New programmers often run into these issues:
- Forgetting prompts, leaving users uncertain
- Not handling invalid input types
- Mixing
>>withstd::getline()incorrectly - Assuming all user input will always be valid
Recovering from Invalid Input
If formatted extraction fails (e.g., user types letters for a number), clear the error state and discard the bad input before retrying: