简体   繁体   中英

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.

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.

Should work like this,

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM