28 Beginner The Hundred
The Name That Came Back Empty
the prompt nobody got to answer
#include <iostream>
#include <sstream>
#include <string>
int main() {
// pretend this is std::cin and the user typed: 42 <Enter> Ada Lovelace <Enter>
std::istringstream in("42\nAda Lovelace\n");
int age;
std::string name;
in >> age;
std::getline(in, name);
std::cout << "age = " << age << '\n';
std::cout << "name = [" << name << "]\n";
}
Run it. Who is Ada?
Answer
age = 42, then name = []. The name comes back empty — and no error is reported:
the stream is still good().
Why¶
in >> age reads digits until it meets something that isn't one, then stops — it does
not consume the character that stopped it. The '\n' after 42 is still sitting in the
buffer. std::getline then does its job flawlessly: it reads up to the next '\n', finds
one immediately, extracts zero characters, throws that newline away, and hands back an
empty string. Nothing failed, so nothing complains — and the next getline is the one
that finally returns Ada Lovelace. On a real std::cin it looks even stranger: the
program seems to skip your question entirely, because the Enter you pressed after the
number was already queued up as the answer. -Wall -Wextra is silent; both calls did
exactly what they promise.
The fix¶
Get rid of the leftover newline before switching modes:
in >> age >> std::ws; // skip whitespace, then read
in.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // or: drop the line (<limits>)
std::ws also swallows blank lines and leading spaces, so reach for ignore when those
carry meaning — it discards exactly one line's worth. Simplest of all: read every input
with getline and convert the line yourself with std::stoi.
Takeaway: >> stops at the delimiter and leaves it behind, getline stops after
it — mix the two and the newline you left becomes the line someone else reads.
Try it: g++ -std=c++17 main.cpp -o demo && ./demo