使用'cin'读取'unsigned int' [英] Reading 'unsigned int' using 'cin'

查看:208
本文介绍了使用'cin'读取'unsigned int'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 cin 读取 unsigned int ,如下所示:

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

using namespace std;

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

// UINT_MAX = 4294967295
cout< 请输入介于0和<< UINT_MAX<< :<< endl

cin>>数;

//检查数字是否是有效的无符号整数
if((number< 0)||((unsigned int)number> UINT_MAX))
{
cout<< 无效号码。 << endl
return -1;
}
return 0;
}

但是,每当输入大于无符号整数 UINT_MAX ),程序显示 3435973836 。如何检查用户提供的输入是否落在 0 UINT_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< 数字太大了! << std :: endl;
}

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


I am trying to read an unsigned int using cin as follows:

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

However, whenever I enter a value greater than the upper limit of unsigned integer (UINT_MAX), the program displays 3435973836. How do I check if the input given by user falls between 0 to UINT_MAX?

解决方案

Two things:

  • Checking if an unsigned integer is < 0 or > UINT_MAX is pointless, since it can never reach that value! Your compiler probably already complains with a warning like "comparison is always false due to limited range of type".

  • The only solution I can think of is catching the input in a string, then use old-fashioned strtoul() which sets errno in case of overflow.

I.e.:

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

Note: strtoul returns an unsigned long; there's no function strtou(), returning an unsigned int.

这篇关于使用'cin'读取'unsigned int'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆