while loop - C++ Cin ignores non-integers? -
this question has answer here:
i have question c++. i've been searching answer , have found nothing fix code. decided ask myself. problem is, made little program output day of week, if user inputs 1, output 1st day of week (sunday or monday, depends on live) , on , forth. however, if user inputs example, 8, program output "please choose number between 1 , 7!" however, problem when user inputs character or random word, loop "please choose number between 1 , 7!" forever.
#include <iostream> #include <windows.h> #include <string> using namespace std; int main() { int input; { cin >> input; switch (input) { case 1: cout << "sunday" << endl; break; case 2: cout << "monday" << endl; break; case 3: cout << "tuesday" << endl; break; case 4: cout << "wednesday" << endl; break; case 5: cout << "thursday" << endl; break; case 6: cout << "friday" << endl; break; case 7: cout << "saturday" << endl; break; default: cout << "please choose number between 1 , 7!" << endl; // if user chooses number not 1-7 output this. if input not int , example "a", loop forever. break; } } while (true); return 0; }
statement cin >> input
may fail, e.g. if user inputs cannot converted integral value, or if stream reaches eof
(e.g. ctrl-d or ctrl-z in standard input). if cin >> input
fails, 2 things happen: first, error state set, indicating type of failure. second, expression returns false
, indicating no value has been written input
.
so should check result of cin >> ...
before going ahead. and, if detect invalid input, have reset error flag (using cin.clear()
) before reading in again, , might want skip invalid input (using cin.ignore(...)
) in order avoid reading in same (invalid) input again , again:
int main() { int input; while (true) { while (!(cin >> input)) { if (cin.eof()) { cout << "user terminated input." << endl; return 0; } cout << "invalid input (not number); try again." << endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); } // here on, may rely user has input number. cout << input; // ... code goes here } return 0 ; }
note should allow program exit when reaching eof
. otherwise, may run infinite loop when pass file invalid content input program (e.g. myprogram < input.txt
).
Comments
Post a Comment