cin >> fails with bigger numbers but works with smaller ones?

我与影子孤独终老i 提交于 2019-12-28 04:33:15

问题


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

It simply skips the step.


回答1:


Try:

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

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.

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.




回答2:


That's probably because the big value is too big to fit into a variable of int type on your system. Try just assigning the big value to your variable and see what happens.

To fix it, change the type of the variable to a wider type, like long or long long.




回答3:


The maximal number representable by an int depends on the number of bits it is represented. Usually, it's 32-bits, ie. the maximal number is 2147483647, which is smaller than the number you typed.




回答4:


When the formatted input functions fail in some form, they set std::ios_base::failbit and leave the original value in the argument unchanged. There are different failures and overflows are considered one sort of failure. I recall a discussion about different errors being indicated in different ways but I din't recall the outcome. The best bet may be to make sure errno is cleared before calling any of the input functiins and checking errno for ERANGE to distinguish an overflow from a format error.



来源:https://stackoverflow.com/questions/13474989/cin-fails-with-bigger-numbers-but-works-with-smaller-ones

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!