DevAcademia lesson/C++ Basics
User Input Strings
Topic progressTopic 31 of 109 - 28% complete
~8 min lesson17 learning blocks4 code examples1 checks/interactions
Lesson outline
Reading Strings with cin
The extraction operator (>>) reads input only until the first whitespace character. This makes it suitable for single-word input:
Reading Entire Lines
Use std::getline() when you need to read an entire line of text, including spaces:
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().
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.
Robust Input Tips
- Always check the result of input operations (e.g.,
if (!(std::cin >> age))) to handle invalid input gracefully. - Prefer
std::getlinefor free-form text (names, addresses) and then parse, rather than mixing many formatted extractions. - Be mindful of locale/encoding if reading non-ASCII text.
Was this topic clear?