c++ - 为什么 std::stoul 转换负数?

标签 c++ c++11

如图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/

相关文章:

regex - 流上的C++正则表达式

c++ - 移除 vector 元素使用 vector<bool> 中的条件

c++ - 如何确保所有从属线程都等待条件变量?

c++ - C++11 中的函数式编程,F# 风格

c++11 - 可变参数模板+静态数组

c++ - 将 if 语句与指针一起使用时出现段错误(BST 树)

c++ - 重载不适用于 <<

c++ - C++服务的自动延迟启动

c++ - 使用一个 for 循环如何迭代和测试迭代器值?

c++ - Visual Studio C/C++ 如何与远程设备一起工作?