سؤال

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.

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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

Should work like this,

int cost; 
while (!(cin >> cost) 
{  
  cout << "Enter a number:";  
  cin.ignore(10000, '\n');   
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top