std::string answer;
int answerint;
while (std::getline(std::cin, answer))
{
std::istringstream iss(answer);
char c; // seek non-whitespace after the number?
if (!(iss >> answerint) || (iss >> c))
answerint = 0;
switch (answerint)
{
...as you had...
}
}
The code above uses getline
to ensure a complete line of text is parsed into answer
, after which it creates a distinct std::istringstream
from that single line. That way, we can use >>
knowing it won't skip over newlines are consume or wait for further input.
if (!(iss >> answerint) || (iss >> c))
checks whether there isn't a number to parse into answerint
, or after having parsed a number an additional non-whitespace character appears on the line. For example, the line typed might have been 2r
- we'll consider that an error and reprompt for a selection, assigning 0
to answerint
to ensure we reach the default
label in the switch
, thereby printing cout << "\nPlease choose from the list";
which seems as appropriate for 2r
as for 99
or whatever....
Using getline
and a separate istringstream
this way, you can reliably attempt parsing of the next line of input from a known state.