I'm using std::stoi in following manner
int ConvertToInt( const std::string& aVal )
{
int lVal = std::stoi( aVal, nullptr, 0 );
return lVal;
}
Third argument in std::stoi was provided as 0 to convert automatically both DEC and HEX values.
I also use try-catch structure to catch std::invalid_argument, std::out_of_range and ( ... ) althought when I provide number as 0xgg no exception is thrown and the number is converted to 0 which is not my intention.
Is it possbile to catch digits, which are out of range and throw some exception ?
CodePudding user response:
std::stoi
parses the string until an invalid character is encountered, which is interpreted to be the end of the integer.
Is it possbile to catch digits, which are out of range and throw some exception ?
Yes. You can use the pos
argument. After the conversion, the pointed integer will contain the index of the first unconverted character. If the *pos
is not equal to the size of the input, then there are unconverted characters, which must have not been valid. You can throw an exception in such case.