c++ getline() isn’t waiting for input from console when called multiple times

The problem is you are mixing calls to getline() with the use of the operator >>.

Remember that operator >> ignored leading white space so will correctly continue across lines boundaries. But stops reading after the input has successfully been retrieved and thus will not swallow trailing ‘\n’ characters. Thus if you use a getline() after a >> you usually get the wrong thing unless you are careful (to first remove the ‘\n’ character that was not read).

The trick is to not use both types of input. Pick the appropriate one and stick to it.

If it is all numbers (or objects that play nice with operator >>) then just use operator >> (Note string is the only fundamental type that is not symmetric with input/output (ie does not play nicely)).

If the input contains strings or a combination of stuff that will require getline() then only use getline() and parse the number out of the string.

std::getline(std::cin, line);
std::stringstream  linestream(line);

int  value;
linestream >> value;

// Or if you have boost:
std::getline(std::cin, line);
int  value = boost::lexical_cast<int>(line);

Leave a Comment