c++ - cin for an int inputing a char causes Loop that is supposed to check input to go wild -


this function of game ask input , cin "iauswahl"! while loop checks if 1 of values want 1-9 if not activates , supposed ask new input. witch int. if input char r go crazy , keep giving me cout , skip cin! questions why , how stop it?

void zug(string sspieler, int idran){     int iauswahl;     char cxo = 'o';      if (idran == 1)     {         cxo = 'x';     }      cout << sspieler << ", sie sind zug. bitte waehlen sie eins der felder.\n" << endl;     grafik();     cout << "sie sind >> " << cxo << " <<." << endl;     cin >> iauswahl;     cout << endl;      while (          iauswahl != 1          && iauswahl != 2          && iauswahl != 3          && iauswahl != 4          && iauswahl != 5          && iauswahl != 6          && iauswahl != 7         && iauswahl != 8          && iauswahl != 9     )     {         cout << "kein gültiges feld bitte wählen sie noch einmal!\n" << endl;         cin >> iauswahl;     }     feldfuellen(iauswahl, cxo); } 

when error occurs when reading stream, error flag gets set , no more reading possible until clear error flags. that's why infinite loop.

cin.clear(); // clears error flags // line discards input waiting in stream cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 

also, it's wrong use results of input operation if don't know whether read succeeded in first place. can't make assumptions value of iauswahl. that's 1 of made errors newbies using streams. check if input operation ok. done using operator>> in boolean context:

if (cin >> some_obj) {     // evaluates true if succeeded } else {     // went wrong } 

and, oh my, line

while (iauswahl != 1 && iauswahl != 2 && iauswahl != 3 && iauswahl != 4 && iauswahl != 5 && iauswahl != 6 && iauswahl != 7 && iauswahl != 8 && iauswahl != 9) 

can this:

while (iauswahl < 1 || iauswahl > 9) 

a correct loop this:

while (true) {     if ((cin >> iauswahl) && (iauswahl >= 1) && (iauswahl <= 9)) break;     std::cout << "error, try again\n";     cin.clear();     cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } 

Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -