gpt4 book ai didi

c++ - 负数的strtoul

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:43:12 28 4
gpt4 key购买 nike

以下 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com