What are the rules of the std::cin object in C++?

What is happening here is that std::cin >> firstName; only reads up to but not including the first whitespace character, which includes the newline (or '\n') when you press enter, so when it gets to getline(std::cin, articleTitle);, '\n' is still the next character in std::cin, and getline() returns immediately.

// cin = "Bloggs\nJoe\nMan of Steel, Woman of Kleenex\n"
std::cin >> lastName;
std::cin >> firstName;
// firstName = "Joe", lastName = "Bloggs", cin = "\nMan of Steel, Woman of Kleenex\n"
getline(std::cin, articleTitle);
// articleTitle = "", cin = "Man of Steel, Woman of Kleenex\n"

Adding ‘std::cin >> std::ws‘ (ws meaning whitespace) before your calls to getline() fixes the problem:

std::cin >> firstName >> std::ws;
getline(std::cin, articleTitle);

But it is easier to see where you missed it if you do it in the argument:

std::cin >> firstName;
getline(std::cin >> std::ws, articleTitle);

Leave a Comment