C++20 sections · 1024 units
Open in Course

The Newline Problem

Handling leftover newlines

Mixing cin >> and getline causes a common problem. After cin >> n;, a newline remains in the buffer. The next getline reads this leftover immediately, returning empty. Example: read number then name.

cin >> age; leaves newline. getline(cin, name); reads empty line up to that newline. Name ends up empty even though user typed something. Fix with cin.ignore(); after cin >>. This discards the leftover newline.

Now getline waits for fresh input. Always add cin.ignore() when switching from >> to getline.