Axel Kennedal
Axel Kennedal

Reputation: 555

Checking for input type fails, C++

I have this code which is supposed to fool-proof the program from users entering something else but an integer. I wrote this code based on several sources online but for some reason it doesn't work.

                int cost;                    
                cin >> cost;

                if (!(cin>>cost)) {
                    cout << "Enter a number: ";
                    cin >> cost;
                    cin.ignore(10000, '\n');
                }

The prompt which is supposed to show up when you enter an incorrect type doesn't appear and the program terminates. I've tried moving around and adding cin.ignore() to other places, I've also tried if(cin.fail()) with no success.

Upvotes: 0

Views: 113

Answers (3)

DesignIsLife
DesignIsLife

Reputation: 540

Should work like this,

int cost; 
while (!(cin >> cost) 
{  
  cout << "Enter a number:";  
  cin.ignore(10000, '\n');   
}

Upvotes: 0

Massa
Massa

Reputation: 8972

you might do like @MatsPetersson and @40two mentioned above, but I would do that this way:

const int MAX_TRIES = 3;
int cost;
cout << "Enter a number: ";
for( int tries = 0; !(cin >> cost) && (tries < MAX_TRIES); ++tries ) {
  cin.clear();
  cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
  cout << "This is not a number, try again: ";
}

Upvotes: 0

Dimitrios Bouzas
Dimitrios Bouzas

Reputation: 42909

do the following:

    int cost;
    cout << "Enter a number: ";                
    if(!(cin >> cost) {
      cin.clear();
      cin.ignore(10000, '\n');
    }

Reason : You have a redundant cin statement.

Upvotes: 3

Related Questions