C++ - User Input
Overview
Estimated time: 25–35 minutes
Read input from the terminal with std::cin and std::getline. Handle whitespace and type parsing.
Learning Objectives
- Use std::cin to read numbers and words.
- Use std::getline to read entire lines.
- Handle leftover newlines and input validation basics.
Prerequisites
Reading numbers and words
#include <iostream>
#include <string>
int main(){
int age; std::string name;
std::cout << "Age: "; std::cin >> age;
std::cout << "Name: "; std::cin >> name; // reads up to whitespace
std::cout << name << " " << age << "\n";
}
Reading whole lines
#include <iostream>
#include <string>
int main(){
std::string line;
std::getline(std::cin, line);
}
Common Pitfalls
- Mixing operator>> with getline leaves a trailing newline in the buffer; consume it before getline.
Checks for Understanding
- How do you read a full line with spaces?
Show answers
- Use std::getline(std::cin, line).
Exercises
- Prompt for first and last name separately using >> and then print the full name.
- Prompt for a line of input and count the number of words.