c++ - why would cin.fail() pass input=100a if 'input' is an int? -
int main(void) { int valid_input(); int ll_input=0; int resp; hash_table obj; int bucket; while(1) { ll_input=valid_input(); if(ll_input>10) { break; } obj.insert(ll_input); } obj.print_ll(); return 0; } int valid_input() { int input; printf("\n\renter value: "); std::cin >> input; while(std::cin.fail()) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); printf("\n\rbad entry!\n\renter value: "); std::cin>>input; } return input; }
the above code, works correctly alphanumeric combinations, rejects user inputs a,10aa,1003abc, etc. however, on inputs 100a, 100b, etc, passes. reason this?
cin >> input
stops reading finds non number, "100a" interpreted 2 tokens: "100" , "a".
"100" converted int
, exits while(std::cin.fail())
loop. leaves "a" sitting in stream bedevil next read of cin
.
the quick way catch this, (quick in terms of writing , explaining, not fastest execute if input error-prone)
std::string token; while (true) // or countdown kick out moronic { cin >> token; try { return std::stoi(token); } catch (...) // don't care why std::stoi failed { } }
faster approaches, if errors expected, use strtol
or similar , skip exception handling overhead.
Comments
Post a Comment