0

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.

2
  • You have an extra cin before the if and in the if. Commented Apr 23, 2014 at 18:56
  • Do you actually mean to have cin >> cost; if (!cin >> cost) ...? Commented Apr 23, 2014 at 18:56

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

Remember, there is no "above" with answers, as the order can change based on sorting and votes. Instead, you can link to the answers.
After the loop, you need something to determine that "tries" ran out and there is still "no good answer"...
@MatsPetersson if( cin ) { /* cost has a number */ } else { /* boohoo */ } :D
0

Should work like this,

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.