如图http://ideone.com/RdINqa , std::stoul
不会为负数抛出 std::out_of_range
,而是将它们包裹起来。为什么是这样?似乎 -4 超出了 unsigned long
类型的范围,所以它应该抛出。
最佳答案
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.
这里的“转换后的值”是strtoul
返回的值。当然,它是 unsigned long
类型,因此不能超出 stoul
返回类型的可表示值范围,它也是 无符号长整型
。
据我所知,只有 stoi
可以抛出 out_of_range
,因为它返回 int
但使用 strtol
返回 long
。
此外,C标准指定strtoul
的方式,要求接受字符串"-4"
并返回一个等于-(unsigned long )4
。为什么这样指定,我不知道。
关于c++ - 为什么 std::stoul 转换负数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19327845/