c++ - go back to first instruction when there is an error -
i creating simple console application obtain user input integer.
i want condition should integer , should not more 3 , not less 0.
the code came far is:
#include <iostream> #include <sstream> #include <string> using namespace std; int main() { int uinval; while (true) { string tempoval; cout << "please enter value between 0-3:\n>"; cin >> tempoval; stringstream ss(tempoval); if (ss >> uinval) { break; cout << "entered invalid value"; } while (true) { if (uinval < 0 || uinval > 3) break; cout << "value must between 0-3"; } cout << "you have entered:" << uinval; return 0; }
this works when input non-integer value a,b,c,d. not work when input -1 or 4 value.
i not sure, maybe confused myself while loops.
this incorrect:
while(true){ if(uinval < 0 || uinval > 3) break; cout <<"value must between 0-3"; }
you check condition on uinval
repeatedly, without giving user chance enter new value.
to fix problem, remove second loop, , replace
if(ss >> uinval) { break; }
inside first loop with
if(ss >> uinval && uinval >= 0 && uinval < 4) { break; }
Comments
Post a Comment