문제

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