Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::stoul convert negative numbers?

Tags:

c++

c++11

As shown in http://ideone.com/RdINqa, std::stoul does not throw a std::out_of_range for negative numbers, but wraps them around. Why is this? Seems like -4 is out of the range of the type unsigned long so it should throw.

like image 552
Kal Avatar asked Oct 11 '13 21:10

Kal


People also ask

Does Strtol work with negative numbers?

If the value is negative, the strtol() function will return LONG_MIN, and the strtoll() function will return LONGLONG_MIN. If no characters are converted, the strtoll() and strtol() functions will set errno to EINVAL and 0 is returned.

How do you make a negative positive in CPP?

Click Compiler Settings, and inside the tab opened click Compiler Flags. Scroll down until you find: Have g++ follow the C++ 11 ISO C++ language standard [-std=c++11]. Check that and then hit OK button. Restart Code::Blocks and then you are good to go!

What is std :: Stoul?

std::stoul, std::stoullInterprets an unsigned integer value in the string str .

Does Atoi convert negative numbers?

You have to copy minus sign from last to first position. Otheriwse atoi cannot return negative value.


1 Answers

21.5 Numeric conversions

unsigned long stoul(const string& str, size_t *idx = 0, int base = 10);

Effects: ...call[s] strtoul(str.c_str(), ptr, base) ... returns the converted result, if any.

Throws: ...out_of_range if the converted value is outside the range of representable values for the return type.

"Converted value" here is the value returned by strtoul. Which, of course, is of type unsigned long and so can't be outside of the range of representable values for the return type of stoul, which is also unsigned long.

As far as I can tell, only stoi can throw out_of_range, because it returns int but uses strtol which returns long.

Further, the way C standard specifies strtoul, it is required to accept the string "-4" and return a value equal to -(unsigned long)4. Why it's specified this way, I don't know.

like image 191
Igor Tandetnik Avatar answered Oct 27 '22 13:10

Igor Tandetnik