c++ - 使用 'unsigned int' 读取 'cin'

标签 c++ windows int unsigned cin

我正在尝试使用 cin 读取 unsigned int,如下所示:

#include <limits.h>
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
    unsigned int number;

    // UINT_MAX = 4294967295
    cout << "Please enter a number between 0 and " << UINT_MAX << ":" << endl;

    cin >> number;

    // Check if the number is a valid unsigned integer
    if ((number < 0) || ((unsigned int)number > UINT_MAX))
    {
        cout << "Invalid number." << endl;
        return -1;
    }
    return 0;
}

但是,每当我输入一个大于无符号整数上限(UINT_MAX)的值时,程序就会显示3435973836。如何检查用户给出的输入是否介于 0UINT_MAX 之间?

最佳答案

两件事:

  • 检查无符号整数是否为 < 0 或 > UINT_MAX 毫无意义,因为它永远无法达到该值!您的编译器可能已经发出警告,例如“由于类型范围有限,比较总是错误的”。

  • 我能想到的唯一解决方案是在字符串中捕获输入,然后使用老式的 strtoul() 设置 errno 以防溢出。

即:

#include <stdlib.h>

unsigned long number;
std::string numbuf;
cin >> numbuf;
number = strtoul(numbuf.c_str(), 0, 10);
if (ULONG_MAX == number && ERANGE == errno)
{
    std::cerr << "Number too big!" << std::endl;
}

注意:strtoul返回一个unsigned long;没有函数 strtou(),返回一个无符号整数。

关于c++ - 使用 'unsigned int' 读取 'cin',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9574771/

相关文章:

c++ - OpenMP 线性加速

c++ - 自动选择按值传递还是按引用传递

c++ - 程序在返回 cstring 时返回垃圾值

Windows alt + tab 导致窗口模式

java - 从 String 转换为 int 再转换为 Vaadin 时出错

c# - 如何检查计算是否在整数较高和较低范围内

c++ - 使用 C++ 泛型编程对 x 和 y 类型的所有排列执行 func(x,y) 的运行时调用

c++ - 当鼠标悬停在某个控件上时,如何设置自定义光标?

.net - 必需的是 "not matching"如果不是至少 1 个字符在 3 的序列中匹配,否则可选的正则表达式

java - 检查字符串中的数字,当字符串以 0 开头时不起作用