Reputation: 61
So I am trying to allow a user to make a selection but Im having issue. the following lines
cout << "\nWhat would you like to do? " << endl
<< "(1) Display the entire List" << endl
<< "(2) to exit" << endl;
getline(cin,answer);
answerint=stoi(answer);
switch (answerint) {
case 1:
showLIST(myLIst);
break;
case 2:
return;
default:
cout << "\nPlease choose from the list";
}
So this works fine if the user chooses a integer, but it barfs if a character is received. How can I make this less breakable?
Upvotes: 0
Views: 146
Reputation: 106246
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.
Upvotes: 0
Reputation: 154035
It seems you want something like this:
if (std::cin >> answerint) {
switch (answerint) {
// ...
}
}
Converting the integer directly from the stream puts the stream into failure state in case something different than an int
is entered. You may want to add a manipulator to make sure there are no non-space characters on the end of the line.
Upvotes: 1