Reading Full Lines with getline in C++
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.
getline reads spaces too
std::getline(std::cin, name); fills name with the entire line, spaces included, dropping the trailing newline.
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.
ignore() clears the way
std::cin.ignore(10000, '\n'); after >> input discards up to the next newline so the subsequent getline starts fresh.
Looping over lines
while (std::getline(std::cin, line)) processes standard input line by line until end-of-file — the standard text-filter pattern.
#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;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.