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?
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 */
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With