如何检查整数范围?

问题描述 投票:-2回答:6

我有这个代码,但是当我输入一个超过整数值的值时会打印出来。我实际上有条件来检查范围。如何使它工作?我知道这对你来说很容易。我只是忘记了C ++中的一些东西,我没有时间。

#include <iostream>
#include <typeinfo>
#include<cfloat>
#include<climits>

using namespace std;

int    g1, g2;
string text  = " year";
string text2 = " age";

int main() {
  g1 = 2100000000000000000000000;
  g2 = 16;

  if (g1 < INT_MIN || g1 > INT_MAX) {
    std::cout << "Please enter an integer";
  } else {
    std::cout << g1 << text;
    std::cout << g2 << text2;
  }

  return 0;
}
c++
6个回答
4
投票

因为C ++故意模糊了像int这样的原始类型的最小和最大尺寸,所以像2100000000000000000000000这样的大整数文字是危险的平台依赖。

您的程序甚至可能格式不正确,因此根本无法编译。幸运的是,检查用户输入与整数文字没有任何关系。前者发生在运行时,后者是编译时方面。

这意味着您的示例代码是不切实际的场景。在实际程序中,g1的值不是编译时常量,而是用户输入的数字。

一个很好的做法是首先让用户使用std::string将数字输入std::getline,然后使用std::stoi将字符串转换为int

如果您遵循这种做法,所有错误检查都由标准库执行,您根本不必使用INT_MININT_MAX或其C ++对应的std::numeric_limits<int>::min()std::numeric_limits<int>::max()

例:

#include <iostream>
#include <string>

auto const text  = " year";
auto const text2 = " age";

int main() {
  try {
    std::string input;

    std::getline(std::cin, input);
    auto const g1 = std::stoi(input);

    std::getline(std::cin, input);
    auto const g2 = std::stoi(input);

    std::cout << g1 << text;
    std::cout << g2 << text2;
    std::cout << '\n';

  } catch (std::out_of_range const&) {
    std::cout << "Please enter an integer\n";
  }
}

最棒的是,它还会检测其他类型的不良用户输入,例如当用户输入字母而不是数字时。扩展此示例代码中的错误处理以捕获其他类型的异常留给读者练习。


3
投票

在C ++中,您应该使用std :: numeric_limits(来自<limits>)。以C开头的标题<climits>的名称表明它是一个旧的C头,左侧是兼容性(前limits.h)。你忘记了表达式中的括号,它将被错误地评估。文字对于int来说太大了。值实际上不能超过绑定类型的边界

http://en.cppreference.com/w/cpp/types/numeric_limits

#include <iostream>
#include <typeinfo>
#include<limits>

long long g1, g2;

int main() 
{
  //...

  if ((g1 > std::numeric_limits<int>::lowest()) 
       || (g1 < std::numeric_limits<int>::max())) 
  {
       //...
  } 

  return 0;
}

你必须处理来自cin的输入,如果用户做错了就会重置输入。要实际(关闭蠕虫)检查范围,您需要更大(可以蠕虫)的存储。考虑这个功能:

int  getInt()
{
    while (1) // Loop until user enters a valid input
    {
        std::cout << "Enter an int value: ";
        long long x;  // if we'll use char, cin would assume it is character
        // other integral types are fine
        std::cin >> x;

        if (std::cin.fail()) // has a previous extraction failed?
        {
            // yep, so let's handle the failure, or next >> will try parse same input
            std::cout << "Invalid input from user.\n";
            std::cin.clear(); // put us back in 'normal' operation mode
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); // and remove the bad input
        }
        // Thechnically you may do only the above part, but then you can't distingusih invalid format from out of range
        else if(( x  > std::numeric_limits<int>::max()) ||
            ( x  < std::numeric_limits<int>::min()))
        {
            std::cout << "Invalid value.\n";
        }
        else // nope, so return our good x
            return x;
    }
}

如果istream无法将输入解析为所需类型,则缓冲区的剩余内容将保持不变,直到您清除它或请求将导致成功的操作为止。例如,您可以检查用户是否输入了浮动..或者他是否输入了停止程序的命令。


1
投票

你想做什么真的很难检查。就像检查是否已将负数保存为无符号整数一样。一旦将其保存在那里,由于存储在该变量内的信息的不同表示,信息将丢失并且值被破坏。

我不确定如果你试图保存一个大于变量空间的值会发生什么,但最好的选择是将它作为字符串加载并用std :: stoi()解析它,如果这些值会给你错误超过了int范围。


0
投票

如果您的目标是检查输入数字是否在整数范围内?然后您可以将输入数字作为字符串,使用字符串函数可以检查数字是否在范围内。这是一个实现。

std::string inputNum = ""; //input number as string
std::cin>>inputNum; //assuming you are going to input numbers only
std::string maxNum = std::to_string(INT_MAX); //2147483647
std::string minNum = std::to_string(INT_MIN); //-2147483648

if(inputNum[0] == '-') //negative number
{
    /* if num of digits are more than min Number's digit
     * then the number is already out of range 
     * if num of digits are equal then you would have 
     * to check whether it is less than the min number or not
     * all numbers with lesser number of digits are in the range
    */
    if(inputNum.length() > minNum.length()) 
        std::cout<<"Not an integer" << std::endl;
    else if(inputNum.length() == minNum.length())
        if(inputNum > minNum)
            std::cout<<"Not an integer" << std::endl;
        else
            std::cout<<"Integer" << std::endl;
    else
        std::cout<<"Integer" << std::endl;
}

else //positive number
{
    if(inputNum.length() > maxNum.length())
        std::cout<<"Not an integer" << std::endl;
    else if(inputNum.length() == maxNum.length())
        if(inputNum > maxNum)
            std::cout<<"Not an integer" << std::endl;
        else
            std::cout<<"Integer" << std::endl;
    else
        std::cout<<"Integer" << std::endl;
}

0
投票

只需检查输入是否成功:

#include <iostream>


int main()
{
    int val;
    if (std::cin >> val)
        std::cout << "value is " << val << "\n";
    else
        std::cout << "value input failure\n";

    return 0;
}

Live on Coliru


-2
投票

c ++具有头文件,对于您正在使用的实现,不同的数据类型有一些最小值和最大值。

看这里。此外,你必须使用64位整数,看它是否小于那么最大或大于32位整数的最小值,那么你可以转换。

© www.soinside.com 2019 - 2024. All rights reserved.