2

我需要:

1)找出我当前系统上的最大无符号整数值是多少。我没有在limits.h上找到它。写作安全unsigned int maxUnsInt = 0 - 1;吗?我也尝试unsigned int maxUnsInt = MAX_INT * 2 + 1返回正确的值,但编译器显示有关 int 溢出操作的警告。

2)一旦找到,检查一个 C++ 字符串(我知道它只由数字组成)是否超过了我系统上的最大 unsigned int 值。

我的最终目标是使用 atoi 将字符串转换为无符号整数,当且仅当它是有效的无符号整数时。我宁愿只使用标准库。

4

3 回答 3

3

应该有一个#define UINT_MAXin <limits.h>; 如果没有,我会感到非常惊讶。否则,保证:

unsigned int u = -1;

将导致最大值。在 C++ 中,您也可以使用 std::numeric_limits<unsigned int>::max(),但在 C++11 之前,这不是一个整数常量表达式(这可能是也可能不是问题)。

unsigned int u = 2 * MAX_INT + 1;

不保证是任何东西(至少在一个系统上 MAX_INT == UMAX_INT)。

关于检查字符串,最简单的解决方案是使用strtoul,然后验证errno和返回值:

bool
isLegalUInt( std::string const& input )
{
    char const* end;
    errno = 0;
    unsigned long v = strtoul( input.c_str(), &end, 10 );
    return errno == 0 && *end == '\0' && end != input.c_str() && v <= UINT_MAX;
}

如果您使用的是 C++11,您还可以使用std::stoul,它会在溢出时引发std::out_of_range异常。

于 2013-02-15T11:25:47.880 回答
2

numeric_limits对各种数字类型有限制:

unsigned int maxUnsInt = std::numeric_limits<unsigned int>::max();

stringstream可以将字符串读入任何支持的类型operator>>并告诉您它是否失败:

std::stringstream ss("1234567890123456789012345678901234567890");

unsigned int value;
ss >> value;

bool successful = !ss.fail();
于 2013-02-15T11:14:54.210 回答
1

根据这个你不需要计算它,只需使用适当的常数,这种情况应该是UINT_MAX

很少的笔记。

与 c++ 相比,这似乎更像是一种交流方式,但既然你说你想使用atol我就坚持下去。c++ 将numeric_limits按照 Joachim 的建议使用。然而,c++ 标准也定义了类似 c 的宏/定义,因此使用起来应该是安全的。

此外,如果您希望它采用 c++ 方式,则可能更喜欢使用stringstream(它是标准 c++ 库的一部分)进行转换。

最后,我故意不发布显式代码解决方案,因为它看起来像家庭作业,你现在应该很好地从这里开始。

于 2013-02-15T11:07:03.710 回答