C++20 sections · 1024 units
Open in Course

Mixing cin and getline

Common mixing error

If you use cin >> before getline, a leftover newline causes getline to read an empty line immediately. int age; string name; cin >> age; getline(cin, name); looks correct but fails.

When the user types 25 and presses Enter, cin >> age reads 25 but leaves the newline in the buffer. Then getline(cin, name) immediately reads that newline as an empty string.

This happens because cin >> skips leading whitespace but does not consume the newline after the number. The getline sees that newline and finishes instantly.