Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string (char*) to number with error checking using standard library functions?

I can think of 2 ways to convert a string to int: strtol and std::stringstream. The former doesn't report errors (if string is not a representation of a number), the latter throws an exception BUT it is too relaxed. An example:

std::wstring wstr("-123a45");
int result = 0;
try { ss >> result; }
catch (std::exception&) 
{
   // error handling
}

I want to detect an error here because the whole string is not convertible to int, but no exception is being thrown and result is set to -123. How can I solve my task using standard C++ facilities?

like image 689
Violet Giraffe Avatar asked Jan 13 '23 06:01

Violet Giraffe


1 Answers

You erroneously believe that strtol() does not provide error checking, but that is not true. The second parameter to strtol() can be used to detect if the entire string was consumed.

char *endptr;
int result = strtol("-123a45", &endptr, 10);
if (*endptr != '\0') {
    /*...input is not a decimal number */
}
like image 185
jxh Avatar answered Jan 17 '23 16:01

jxh