c++ - why is this not returning true (loop-logic) -
std::string turnsdefined; std::cin >> turnsdefined; bool haspassed; while(haspassed != true){ for(char c : turnsdefined){ if(isdigit(c) != true){ std::cout << "please utilize numbers describe amount of turns you'd do." << std::endl; haspassed = false; break; std::cin >> turnsdefined; }else{ haspassed = true; } } }
i've stumbled upon this. shortened downwards code (by reasonable amount) can seek yourself.
this short programme should check if come in contains (unwanted) letters. thing don't understand: way wrote it, pretty sure if typed test2test it's gonna pass (even though contains letters) because if statement recognize 1 single number , set haspassed true.
i hope create sense of wrote. happy reply farther questions.
bool haspassed not initialized in code. should declare as:
bool haspassed = false; live code here
uninitialized automatic (local , non static) variables contain in-determinant value. reading them prior assigning value results in undefined behavior. (compiler free blunder here in practice may contain true or false or other non-sense value)
editfrom andy newman's comment: status if(isdigit(c) != true) suspectible. because isdigit returns int should avoid comparing true.
isdigit returns non-zero value (true) if character numeric character, 0 (false) otherwise.
you can improve rewrite status as:
if(isdigit(c)) { even if function returns bool, superfluous compare true or false
c++ loops logic
No comments:
Post a Comment