C++ User Input
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:
#include <iostream>
int main() {
int age;
std::cout << "Enter your age: "; // Prompt the user
std::cin >> age; // Read input (formatted extraction)
std::cout << "You are " << age << " years old.";
return 0;
}
Enter your age: 25 You are 25 years old.
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:
#include <iostream>
int main() {
double height, weight;
std::cout << "Enter your height (m) and weight (kg): ";
std::cin >> height >> weight; // Reads two values, skipping whitespace
std::cout << "Height: " << height << "m, Weight: " << weight << "kg";
return 0;
}
Enter your height (m) and weight (kg): 1.75 68.5 Height: 1.75m, Weight: 68.5kg
Building a Simple Calculator
Here’s a simple calculator that adds two numbers entered by the user:
#include <iostream>
int main() {
double num1, num2;
std::cout << "Simple Addition Calculator\n";
std::cout << "Enter first number: ";
std::cin >> num1;
std::cout << "Enter second number: ";
std::cin >> num2;
double sum = num1 + num2;
std::cout << "\nResult: " << num1 << " + " << num2 << " = " << sum << '\n';
return 0;
}
Simple Addition Calculator Enter first number: 12.5 Enter second number: 7.3 Result: 12.5 + 7.3 = 19.8
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:
#include <iostream>
#include <string>
#include <limits>
int main() {
int age{};
std::string name;
std::cout << "Enter your age: ";
std::cin >> age;
// Discard everything up to and including the next newline
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Enter your full name: ";
std::getline(std::cin, name);
std::cout << age << " year old " << name;
return 0;
}
Enter your age: 25 Enter your full name: John Doe 25 year old John Doe
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
// Good practice with a prompt
std::cout << "Please enter item quantity (1-100): ";
std::cin >> quantity;
// Poor practice (no prompt)
std::cin >> quantity;
Common Input Pitfalls
New programmers often run into these issues:
- Forgetting prompts, leaving users uncertain
- Not handling invalid input types
- Mixing >>
with std::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:
#include <iostream>
#include <limits>
int main() {
int n;
while (true) {
std::cout << "Enter an integer: ";
if (std::cin >> n) break; // success
std::cin.clear(); // clear failbit
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // drop bad input
std::cout << "Invalid input, try again.\n";
}
std::cout << "You entered: " << n << '\n';
}