int SelectedIndex;
int i = 4;
while(SelectedIndex > i-1 || SelectedIndex < 0)
{
try{
std::cout <<"please input index from 0 to " << i-1 << std::endl;
std::cin >> SelectedIndex;
}
catch(std::exception& e){SelectedIndex = 999;}
}
Why such loop does not catch error when inputting a string?
How to fix it? I can use std::string and Boost library and reg exp.
Assuming are trying to read in an integer using
std::cinand detect if the user input a string instead:If the user does input a string, an exception will not be thrown (which is why your code doesn’t work as expected). Instead, the input will be left in the buffer, and
cinwill be in an error state. The nextcin >>will read the same value from the buffer in an endless loop, unless you clear the error state and buffer before the next iteration.See this article which explains exactly how to read in an integer (and what happens when a string is input instead) as well as how to clear the error state and buffer.