c++ - 负数的strtoul

标签 c++ c string

以下 C++ 程序调用 strtoul负数 1。因为在任何无符号类型中都不能表示负数,所以我原以为它会失败并返回 0

If no valid conversion could be performed, a zero value is returned.

而是返回一个大的正数

If the value read is out of the range of representable values by an unsigned long int, the function returns ULONG_MAX (defined in <climits>), and errno is set to ERANGE.

#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;}
}

为什么 strtoul 不会失败并为负数返回 0?

最佳答案

对于 documentation,您最好使用 cppreference.com它似乎更准确:

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.

如前所述,可选的加号或减号是有效符号

关于c++ - 负数的strtoul,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37682128/

相关文章:

c - 超出时间限制 - 斐波那契

php - 如何显示 PHP 字符串 "AS IS"(里面的特殊字符)?

Android - 当我在 EditText 中输入时,下一个 EditText 中不计算值?

c++,对 ifstream 使用 get 和 >>

c++ - 字符串文字的大小

c++ - 如何在 C++ 中静态初始化二维数组的数组

python - 多维数组索引C++中的多维数组

c - C 编程 K&R 练习 1-13

c - 有没有文献证明 printf 的 %f 将 float 转换为 double?

javascript - 为什么在 javascript 中使用辅助函数构建字符串?