iostream - How to use cin.fail() in c++ properly -
i'm writing program integer input user cin>>iusersel;
. if user puts in letter, program goes infinite loop. tried prevent code below, program goes infinite loop , prints out "wrong! enter #!". how can fix program?
cin>>iusersel; while (ivalid == 1) { if (cin.fail()) { cin.ignore(); cout<<"wrong! enter #!"<<endl; cin>>iusersel; }//closes if else ivalid = 0; }//closes while
i found information on @ correct way use cin.fail() , c++ cin.fail() question , didn't understand how use them fix issue.
after cin
fails need clear error flag otherwise other input operation non op. clear error flags need call cin.clear()
. code become
cin >> iusersel; while (ivalid == 1) { if (cin.fail()) { cin.clear(); // clears error flags cin.ignore(); cout << "wrong! enter #!" << endl; cin >> iusersel; }//closes if else ivalid = 0; }//closes while
i suggest change cin.ignore();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
in case user enters more 1 letter.
Comments
Post a Comment