1

I need to get an integer from input. I wrote the code:

int price;
    srand((unsigned)time(NULL));
    price = rand() % 1000 + 1;
    int i;
    cout << "Please guess the price(1--1000):" << endl;
    cin >> i;
    while (cin.fail()) {
        cerr << "error"<<endl;
        fflush(stdin);
        //cin.clear();
        //cin.ignore(numeric_limits<std::streamsize>::max());
        //cin.get();
        cin >> i;
    }

I've tried many methods, but if I input a charactere, the result is:

e
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error

I'm so confused, thanks for your help.

liushi
  • 83
  • 7
  • 1
    `cin.fail()` returns` true` when an input failure occurs. In this case it would be an input that is not an integer. If cin fails then the input buffer is kept in an error state. `cin.clear()` is used to clear the error state of the buffer so that further processing of input can take place. Also, you sure you want a `while` there? – stateMachine Aug 15 '20 at 02:00
  • look at [How to avoid char input for an int variable](https://stackoverflow.com/questions/11523569/how-can-i-avoid-char-input-for-an-int-variable) it will help you – Ibram Reda Aug 15 '20 at 02:05
  • See also [cin integer example](https://stackoverflow.com/a/50403158/3422102) – David C. Rankin Aug 15 '20 at 03:58

2 Answers2

0

When a user inputs something other than an integer, then cin.fail(), will return true and the while loop will continue indefinitely with the message error like you are seeing on your console window.

However, when you use cin.clear(); it clears the error flag on cin. So that future inputs will work. cin.clear() will return the state back to a goodbit.

Also you don't even have to use cin.fail() in your case.

You could do something like this instead:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{


    int price;
    srand((unsigned)time(NULL));
    price = rand() % 1000 + 1;
    int i;

    cout << "Please guess the price(1--1000):" << endl;
    cin >> i;

    while (!(cin >> i))
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Please guess the price(1--1000):";

    }
    return 0;
}
Geno C
  • 1,401
  • 3
  • 11
  • 26
  • I use `cin>>i` in the while loop, but it seems that it doesn't work. I think if the user input an integer, so the `cin.fail` will return false. – liushi Aug 15 '20 at 02:09
-1

I think the '\n' char gets into the cin buffer and beside using clear() to reset error state you need to call ignore() to discard '\n' I believe this would work as you intended,

 int price;
    srand((unsigned)time(NULL));
    price = rand() % 1000 + 1;
    int i;
    cout << "Please guess the price(1--1000):" << endl;
    cin >> i;

    while (cin.fail()) {
        cin.clear();
        cerr << "error" << endl;
        cin.ignore();
        cin >> i;
    }
Omid
  • 286
  • 1
  • 5
  • 20