Wednesday, 15 August 2012

while loop - Letters stored as integers -



while loop - Letters stored as integers -

#include <iostream> #include <string> using namespace std; int main() { cout << "please come in integer between 1 , 5" << endl; int x; //selection of menu prompt cin >> x; while (x < 1 || x > 5) //tossing out garbage input { cout << "invalid selection, please create another." << endl; cin >> x; } homecoming 0; }

when run, entering "a" example, enters while loop, not wait user input @ "cin >> x;" , instead loops infinitely through. can explain me why happens , how might prepare issue? can imagine keyboard buffer.

in code, it's possible cin come in error state. if user not come in integer, fail.

that is, if user enters a, cin >> x not set x, , future calls cin >> x not block. see endless loop.

you can check failure status , clear it. before continuing using code similar to:

if (cin.fail()) { cin.clear(); cin.ignore(); cerr << "invalid selection, please create another." << endl; }

while-loop integer letters

No comments:

Post a Comment