Basic Input with cin
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
cout << "You entered: " << number;
return 0;
}
How it works:
cin
reads input until whitespace (space, tab, newline)- The extraction operator
>>
converts input to the variable type - Program waits at
cin
until user presses Enter
Multiple Inputs
Chained Input
int age;
double height;
cout << "Enter age and height: ";
cin >> age >> height;
Input with Prompt
cout << "Enter age: ";
cin >> age;
cout << "Enter height: ";
cin >> height;
String Input
#include <string>
string name;
cout << "Enter your name: ";
cin >> name; // Stops at first whitespace
string fullName;
cout << "Enter full name: ";
cin.ignore(); // Clear input buffer
getline(cin, fullName); // Reads entire line
Key Differences:
Method | Behavior | When to Use |
---|---|---|
cin >> var | Stops at whitespace | Single words/simple input |
getline(cin, var) | Reads entire line | Strings with spaces/multi-word input |
Input Validation
int age;
while (true) {
cout << "Enter age (1-120): ";
if (cin >> age && age >= 1 && age <= 120) {
break;
}
cout << "Invalid input!\n";
cin.clear(); // Clear error state
cin.ignore(1000, '\n'); // Discard bad input
}
Validation Techniques:
- Check stream state with
cin.fail()
- Clear errors with
cin.clear()
- Discard bad input with
cin.ignore()
- Range checking for numeric values
Common Pitfalls
- Mixing
cin >>
andgetline()
:cin.ignore(); // Required after cin >>before getline
- No input validation: Users may enter wrong data types
- Buffer overflow: When reading into fixed-size arrays
char name[20]; cin.getline(name, 20); // Safer than gets()
Advanced Techniques
Character Input
char ch;
cout << "Press a key: ";
ch = cin.get(); // Gets single character
cin.get(ch); // Alternative method
File-like Input
string line;
while (getline(cin, line)) {
if (line.empty()) break;
cout << "Read: " << line << endl;
}