Std::stoi Causing exception

Hello Forum,

Inspired by @Zaptruder 's work, I’ve recently implemented some modifications to my own Bull Cow Game.

Using std::cin, my game receives input in the form of a string and through std::stoi converts that string to an integer that is then stored in “GameDifficulty”. You can see the related code below.

However, if the player enters anything other than a numeral such as a character or a symbol, the game crashes with the following error.

So now I’m asking if anyone here can recommend to me a good way to solve this problem and avoid this error? My first idea is to forego std::stoi and instead write an if or a switch statement that will filter out different kinds of entries. I’m hoping that there might be an easier way however.

Cheers.

for 3 choices, I’d go with “if”. I admit to having being frustrated with standard integer parse routines in languages failing if there is just one bad character (even a space for some of them!) that I have written my own, many times over.

Another option is to put the std:stoi call in a “try” block and catch the std::invalid_argument exception. Googling "c++ exceptions try " should help there. The first result http://www.cplusplus.com/doc/tutorial/exceptions/ looks promising.

Another easy way around this, if you don’t want to do the proper handling of exception as Todd suggests, is to use the C routine ‘atoi’ on an array of chars (as opposed to using the C++ routine for std::string): in this case if it can’t convert the input, it just produces 0. See the reference.
You just need to first make a C-string out of the std::string, but that’s easy.
Hope it helps!

You can avoid using expections by doing a while loop checking std::cin for example

int GameDifficulty;
while(!(std::cin >> GameDifficulty) || GameDifficulty < 1 || GameDifficulty > 3)
{
    std::cout << "Please enter a number between 1-3\n";
    //clear std::cin error flags
    std::cin.clear();
    //read max streamsize up to '\n' and discard it
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

std::cin >> GameDifficulty will return false if it didn’t correctly insert.

1 Like

Hey guys,

I chose to use @DanM’s solution and it worked great.

Thanks everyone for your time.

Cheers.

Privacy & Terms