Learn C++
#include "ioformatting/getline.hpp"

Reading Full Lines with getline in C++

//concept

cin >> stops at the first whitespace, so "Ada Lovelace" arrives as just "Ada". std::getline(cin, line) instead reads everything up to the newline into a std::string — the correct tool for names, sentences, and any input containing spaces.

The classic pitfall is mixing the two: after cin >> age, the Enter keystroke's newline lingers in the buffer and the next getline returns immediately with an empty line. The fix is std::cin.ignore(...) after numeric input to discard the leftover newline before calling getline.

//how it works
1

getline reads spaces too

std::getline(std::cin, name); fills name with the entire line, spaces included, dropping the trailing newline.

2

The leftover-newline trap

cin >> n leaves the Enter newline buffered; a following getline sees it and returns empty — the most common C++ input bug.

3

ignore() clears the way

std::cin.ignore(10000, '\n'); after >> input discards up to the next newline so the subsequent getline starts fresh.

4

Looping over lines

while (std::getline(std::cin, line)) processes standard input line by line until end-of-file — the standard text-filter pattern.

//example
#include <iostream>
#include <string>
 
int main() {
int age = 0;
std::string name;
std::cin >> age;
std::cin.ignore(10000, '\n');
std::getline(std::cin, name);
std::cout << name << " is " << age << std::endl;
return 0;
}
Output
Ada Lovelace is 30
1cin >> age parses 30 but leaves the newline from Enter sitting in the input buffer.
2ignore() eats that leftover newline so getline doesn't mistake it for an empty line of input.
3getline then reads the full Ada Lovelace with its space intact, and the output combines both values.
//use cases
Reading names, addresses, and sentences that contain spaces
Fixing the empty-line bug every beginner hits when mixing >> and getline
Writing line-oriented filters that process stdin until EOF
Parsing CSV-ish lines by getting the whole line first, then splitting it

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.