The following C++ program calls strtoul
of negative 1. Since no negative numbers are representable in any unsigned type, I had expected this to fail and return 0
If no valid conversion could be performed, a zero value is returned.
but instead a large positive number is returned
#include <cstdlib>
#include <iostream>
int main () {
{char s[] = "-1";
for (int b=0; b<17; ++b)
std::cout << "strtoul (unsigned) of " << s
<< " with base arg " << b
<< ": " << strtoul(s,0,b) << std::endl;}
}
Why does strtoul not fail and return 0 for negative numbers?
You better use cppreference.com for documentation it seems to be much more accurate:
if the minus sign was part of the input sequence, the numeric value calculated from the sequence of digits is negated as if by unary minus in the result type, which applies unsigned integer wraparound rules.
and as mentioned there optional plus or minus sign is a valid symbol
Since
0
,{ULONG_MAX}
, and{ULLONG_MAX}
are returned on error and are also valid returns on success, an application wishing to check for error situations should seterrno
to0
, then callstrtoul()
orstrtoull()
, then checkerrno
.
You need to check errno
.
From a different reference: cppreference.com:
Return value
Integer value corresponding to the contents of str on success. If the converted value falls out of range of corresponding return type, range error occurs and ULONG_MAX or ULLONG_MAX is returned. If no conversion can be performed, 0 is returned.
Which is apparently different than cplusplus.com
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.