Back to results for “I/O Streams”
C++ › I/O Streams

What is the difference between >> and std::getline for input?

Intermediate

Answer

operator>> extracts formatted, whitespace-delimited tokens (skipping leading whitespace and stopping at the next whitespace), good for reading numbers/words. std::getline reads an entire line (up to a delimiter, default newline) including spaces. Mixing them requires care because >> leaves the trailing newline in the buffer, which getline then reads as empty.
int n; std::cin >> n;
std::cin.ignore();          // discard leftover newline
std::string line; std::getline(std::cin, line);
Real-world example Reading a number then a full line requires ignoring the leftover newline between >> and getline.

Common follow-ups: Why does mixing >> and getline cause issues? | What does getline include?