Advertisement
Intermediate C++, I/O Streams

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

Short 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.

Save C++ mock interview
Advertisement
AModel 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.
Likely follow-ups
  • Why does mixing >> and getline cause issues? | What does getline include?
Related topics