C++ Checking for an integer.

后端 未结 2 1470
再見小時候
再見小時候 2020-12-18 04:14

New to C++. Having issues correctly looping while handling errors. I am trying to check if user input is an integer, and is positive.

do{
    cout << \         


        
相关标签:
2条回答
  • 2020-12-18 04:46

    In your non-integer branch you are invoking further cin methods so cin.good() gets reset to true.

    You could change your code to something like this:

    while(1) { // <<< loop "forever"
        cout << "Please enter an integer.";
        cin >> n;
    
        if (cin.good())
        {
            if (n < 0) {cout << "Negative.";}
            else { cout << "Positive."; break; }
        }                            // ^^^^^ break out of loop only if valid +ve integer
        else
        {
            cout << "Not an integer.";
            cin.clear();
            cin.ignore(INT_MAX, '\n'); // NB: preferred method for flushing cin
        }
    }
    
    cout << "\ndone.";
    

    or you can simplify it even further like this:

    while (!(cin >> n) || n < 0) // <<< note use of "short circuit" logical operation here
    {
        cout << "Bad input - try again: ";
        cin.clear();
        cin.ignore(INT_MAX, '\n'); // NB: preferred method for flushing cin
    }
    
    cout << "\ndone.";
    
    0 讨论(0)
  • 2020-12-18 04:53
    int n;
    
    while (!(cin >> n)||n<0)//as long as the number entered is not an int or negative, keep checking
    {
    cout << "Wrong input. Please, try again: ";
    cin.clear();//clear input buffer
    
    }
    //only gets executed when you've broken out of the while loop, so n must be an int
    cout << "Positive.";
    
    cout << "\ndone.";//finished!
    

    Should do what you want.

    0 讨论(0)
提交回复
热议问题