C++ User Input
Getting data from users in your C++ programs
⌨️ What is C++ User Input?
User input allows your programs to receive data from users through the keyboard. Using cin, you can read numbers, text, and other data types to make interactive programs.
#include <iostream>
using namespace std;
int main() {
string name;
int age;
cout << "Enter your name: ";
cin >> name;
cout << "Enter your age: ";
cin >> age;
cout << "Hello " << name << ", you are " << age << " years old!" << endl;
return 0;
}
Sample Run:
Enter your name: Alice
Enter your age: 25
Hello Alice, you are 25 years old!
Input Methods
cin >>
Read single words or numbers
int number;
cin >> number; // Read a number
getline()
Read entire lines with spaces
string fullName;
getline(cin, fullName); // Read full line
Multiple Inputs
Read several values at once
int a, b, c;
cin >> a >> b >> c; // Read three numbers
Input Validation
Check if input is valid
if (cin.fail()) {
cout << "Invalid input!";
}
🔹 Basic Input with cin
The cin object, tied to the standard input stream, reads user-provided data from the keyboard
during program execution. It uses the extraction operator (>>), which automatically
skips leading whitespace and reads data based on the variable's type. However, it stops reading at the next
whitespace character. For robust input, especially when expecting multiple words or handling potential errors, it's
often combined with methods like getline() or checked with conditional statements to verify the input
operation succeeded and clear the input buffer if needed.
#include <iostream>
using namespace std;
int main() {
// Reading different data types
int studentId;
double gpa;
char grade;
string firstName;
cout << "Enter student ID: ";
cin >> studentId;
cout << "Enter GPA: ";
cin >> gpa;
cout << "Enter grade (A-F): ";
cin >> grade;
cout << "Enter first name: ";
cin >> firstName;
// Display the information
cout << "\n--- Student Information ---" << endl;
cout << "ID: " << studentId << endl;
cout << "Name: " << firstName << endl;
cout << "GPA: " << gpa << endl;
cout << "Grade: " << grade << endl;
return 0;
}
Sample Run:
Enter student ID: 12345
Enter GPA: 3.85
Enter grade (A-F): A
Enter first name: John
--- Student Information ---
ID: 12345
Name: John
GPA: 3.85
Grade: A
🔹 Reading Full Lines with getline()
std::getline(std::cin, str) reads an entire line of text, including spaces, into a
std::string. It stops at the newline character (which is consumed but not stored). This is
essential for input containing spaces, like names or sentences. A common pitfall is mixing cin >>
and getline: after cin >> number, a newline remains in the buffer, causing
getline to read an empty line. Fix this with
cin.ignore(numeric_limits<streamsize>::max(), '\n') to flush the buffer.
#include <iostream>
using namespace std;
int main() {
string fullName;
string favoriteMovie;
int age;
cout << "Enter your age: ";
cin >> age;
// Clear the input buffer
cin.ignore();
cout << "Enter your full name: ";
getline(cin, fullName);
cout << "Enter your favorite movie: ";
getline(cin, favoriteMovie);
cout << "\n--- Your Information ---" << endl;
cout << "Name: " << fullName << endl;
cout << "Age: " << age << endl;
cout << "Favorite Movie: " << favoriteMovie << endl;
return 0;
}
Sample Run:
Enter your age: 28
Enter your full name: John Smith
Enter your favorite movie: The Matrix
--- Your Information ---
Name: John Smith
Age: 28
Favorite Movie: The Matrix
🔹 Simple Calculator Example
A simple calculator program demonstrates reading numbers and an operator, then performing the corresponding
arithmetic. Use cin to read two double values and a char for the
operator. A switch statement on the operator can handle +, -, *,
/ cases, with special care for division by zero. Display the result formatted clearly. This example
combines input/output, variables, conditionals, and basic error handling—foundational skills for interactive C++
applications. Extend it with a loop for repeated calculations.
#include <iostream>
using namespace std;
int main() {
double num1, num2;
char operation;
cout << "=== Simple Calculator ===" << endl;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter operation (+, -, *, /): ";
cin >> operation;
cout << "Enter second number: ";
cin >> num2;
cout << "\nResult: ";
if (operation == '+') {
cout << num1 << " + " << num2 << " = " << (num1 + num2);
} else if (operation == '-') {
cout << num1 << " - " << num2 << " = " << (num1 - num2);
} else if (operation == '*') {
cout << num1 << " * " << num2 << " = " << (num1 * num2);
} else if (operation == '/') {
if (num2 != 0) {
cout << num1 << " / " << num2 << " = " << (num1 / num2);
} else {
cout << "Error: Division by zero!";
}
} else {
cout << "Error: Invalid operation!";
}
cout << endl;
return 0;
}
Sample Run:
=== Simple Calculator ===
Enter first number: 15
Enter operation (+, -, *, /): *
Enter second number: 4
Result: 15 * 4 = 60
🔹 Input Tips and Best Practices
Robust input handling validates data, recovers from errors, and provides clear prompts. Always guide
users with informative prompts. Validate input range and type; if cin fails, clear the error state and
discard invalid characters. Use loops to reprompt until valid input is received. For numeric input, consider reading
a line with getline() and then parsing with std::stoi or std::stringstream
for better error control. These practices prevent crashes and improve user experience in console applications.
Input Best Practices:
- Use clear prompts: Tell users exactly what to enter
- Use cin.ignore(): Clear buffer when mixing cin >> and getline()
- Validate input: Check if the input is what you expected
- Handle errors: Provide feedback for invalid input
// Good: Clear prompt and validation
cout << "Enter your age (1-120): ";
int age;
cin >> age;
if (age < 1 || age > 120) {
cout << "Please enter a valid age!" << endl;
}