cin>>失败,但数字较大,但适用于较小的数字? [英] cin >> fails with bigger numbers but works with smaller ones?

查看:181
本文介绍了cin>>失败,但数字较大,但适用于较小的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么cin失败,当我输入以下数字时:1 3999999999但它适用于较小的数字,例如:1 5?

Why does cin fail, when I enter numbers like: 1 3999999999 but it works for smaller numbers like: 1 5 ?

int main()
{
    int N, X;
    cout << sizeof(int);

    cout << "Please enter two numbers: ";
    cin >> N >> X;

    vector <int> numbers = vector<int>();

    int currentNumber;

    cout << "Please enter list of numbers: ";
    for ( int i = 0; i < N; i++ )
    {
        cin >> currentNumber;
        if (cin.fail())
            cout << "Something sucks!";
        numbers.push_back(currentNumber);
    }

    sort(numbers.begin(), numbers.end(), Compare(X));

    cout << "The list is now: " << endl;
    for (int i = 0; i < N; i++)
    {
        cout << numbers[i] << " ";
    }
    cout << endl;

    return 0;
}

它只是跳过了这一步。

推荐答案

尝试:

std::cout << std::numeric_limits<int>::max() << std::endl; // requires you to #include <limits>

int 在您的系统上可能是32位带符号的二进制补码,表示它可以表示的最大值是2,147,483,647。您的数字3,999,999,999大于该数字,并且不能用 int 正确表示。 cin 失败,提醒您问题所在。

int on your system is likely a 32-bit signed two's complement number, which means the max value it can represent is 2,147,483,647. Your number, 3,999,999,999, is larger than that, and can't be properly represented by int. cin fails, alerting you of the problem.

可能是系统上的64位整数,如果是,请尝试这样做。您需要一个64位整数来重新设置3,999,999,999。另外,您可以使用 unsigned int ,它可以表示最大为4,294,967,295的数字(同样,在典型系统上)。当然,这意味着您不能表示负数,所以这是一个折衷。

long may be a 64-bit integer on your system, and if it is, try that. You need a 64-bit integer to represet 3,999,999,999. Alternatively, you can use an unsigned int, which will be able to represent numbers as large as 4,294,967,295 (again, on the typical system). Of course, this means you can't represent negative numbers, so it's a trade-off.

这篇关于cin&gt;&gt;失败,但数字较大,但适用于较小的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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