c++ - Why does the following validation code get stuck on the cin.ignore when I enter 1.w and go into an infinite loop when I enter w.1? -
why following validation code stuck on cin.ignore when enter 1.w , go infinite loop when enter w.1?
trying create code validates numerical input. have created code suggestions given on other posts, i'm still having problems.
//the code validation code used check if input numerical (float or integer). #include <iostream> #include <string> #include <limits> // std::numeric_limits using namespace std; int main () { string line; float amount=0; bool flag=true; //while loop check inputs while (flag){ //check valid numerical input cout << "enter amount:"; getline(cin>>amount,line); //use string find_first_not_of function test numerical input unsigned test = line.find_first_not_of('0123456789-.'); if (test==std::string::npos){ //if input stream contains valid inputs cout << "wow!" << endl; cout << "you entered " << line << endl; cout << "amount = " << amount << endl; } else{ //if input stream invalid cin.clear(); // ignore end of line cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } } return 0; }
first, '0123456789-.'
should "0123456789-."
(note double quotes). former multibyte character literal.
when enter 1.w
:
1
gets extractedcin>>amount
..w
extractedgetline
- the stream empty,
ignore
waits inputs
when enter w.1
:
cin>>amount
fails,failbit
gets setgetline
can't extract when stream bad,line
stays emptytest
equalsnpos
, never enterelse
block clear stream- repeat on again
Comments
Post a Comment