D.Fonkaz
D.Fonkaz

Reputation: 55

std::stoi - String with non-numeric characters getting parsed as an integer without throwing exception (c++)

When using std::stoi and passing a string which begins with a number and is followed by non-numeric characters, the string is parsed successfully as an integer, without throwing an exception. E.g "0abcf" is parsed as 0. I want a string to be parsed as an integer only if it contains numeric characters exclusively (i.e "123" but not "12a"), is there an existing function that does this?

Upvotes: 2

Views: 5232

Answers (1)

Max Langhof
Max Langhof

Reputation: 23691

To quote from the documentation:

int stoi( const std::string& str, std::size_t* pos = 0, int base = 10 );
...
the index of [the first unconverted] character will be calculated and stored in *pos, giving the number of characters that were processed by the conversion.

Thus, all you need to do in order to check whether all characters were valid/parsed is to pass a second argument, then check whether this value (the number of converted characters) is equal to the number of characters in the string.

Upvotes: 5

Related Questions