I have a C++ console application that takes input from user by displaying a menu and then acting on it. Everything works fine when the user inputs integer values but when the user inputs a ‘?‘ (which I wanted to handle as a ‘display help’ option) the code starts looping infinitely and does not block on the std::cin>> call. Is this expected? What am I missing here?
int queryAction()
{
while(1) {
char selection;
std::cout << "Action: ";
std::cin >> selection;
switch(selection)
{
//Some code that acts on the selection
...
}
}
}
Follow Up:
If I add std::cin.clear() before the call to cin>> all is good. I guess my follow up question is why is an error state set on input that should be a valid ascii character?
You never check whether reading was successful. A fundamental part of any programming is proper error handling.
std::cin >> selection;will fail if acharcannot be read from the stream or set theeofbitif the end of the source is reached.A simple way to check this is to use something like the following: