User Input Strings
Reading Strings with cin
The extraction operator (>>
) reads input only until the first whitespace character. This makes it suitable for single-word input:
#include <iostream>
#include <string>
int main() {
std::string firstName;
std::cout << "Enter your first name: ";
std::cin >> firstName; // stops at first whitespace
std::cout << "Hello " << firstName;
return 0;
}
Enter your first name: John Hello John
Reading Entire Lines
Use std::getline()
when you need to read an entire line of text, including spaces:
#include <iostream>
#include <string>
int main() {
std::string fullName;
std::cout << "Enter your full name: ";
std::getline(std::cin, fullName);
std::cout << "Hello " << fullName;
return 0;
}
Enter your full name: John Doe Hello John Doe
Mixing cin and getline
When mixing >>
with std::getline()
, the newline left in the input buffer after formatted extraction can cause std::getline()
to read an empty line. Clear the rest of the current line before calling std::getline()
.
#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 name: ";
std::getline(std::cin, name);
std::cout << age << " year old " << name;
return 0;
}
Enter your age: 25 Enter your name: John Doe 25 year old John Doe
Alternative: Skip Leading Newline with std::ws
Instead of a separate ignore
, you can use std::ws
to consume leading whitespace (including the leftover newline) right in the extraction of the stream passed to std::getline
.
#include <iostream>
#include <string>
int main() {
int age{};
std::string name;
std::cout << "Enter your age: ";
if (!(std::cin >> age)) {
std::cerr << "Invalid age\n";
return 1;
}
std::cout << "Enter your name: ";
std::getline(std::cin >> std::ws, name); // std::ws eats leading whitespace/newline
std::cout << age << " year old " << name;
return 0;
}
Robust Input Tips
- Always check the result of input operations (e.g., if (!(std::cin >> age))
) to handle invalid input gracefully.
- Prefer std::getline
for free-form text (names, addresses) and then parse, rather than mixing many formatted extractions.
- Be mindful of locale/encoding if reading non-ASCII text.