Alright, so here's the portion of my code that is giving me a problem. What I want it ot do is to take in a grade, decide if it is a valid grade, and then keep asking for a valid number if it is not. However, it won't even enter the loop, so.... any advice? Ive been programming for a little bit but Im still pretty new, so extra explanations are great! Also this is my first time using booleans in a for loop.
for (bool b_valid=false; b_valid=false ; )
{
cin >> n_grade;
b_valid = true;
if (n_grade>100 || n_grade<0)
{
cout << "Invalid grade: Re-enter a number between 0-100 : " << endl;
cin >> n_grade;
b_valid = false;
}
}
Your condition is an assignment: b_valid=false
. It will evaluate to false and the loop will never execute. You meant
for(bool b_valid = false; b_valid == false; )
^^^^
There is a coding style which mandates that the constant in comparison be the first argument, like if(false == b_valid)
. In this case, if you accidentally typed = , you'd get a compiler error. In any case many compiler give a warning in cases where you had written assignment where a boolean expression was expexted. Either yours wasn't as sofisticated, or you just ignored the warning.
I respectfully disagree with the other (woefully upvoted) answers.
Do not compare a boolean value to either true
or false
.
This is nonsensical, redundant and leads to errors (as in your case).
Simply test the value itself. That is, write ! b_valid
.
Furthermore, using a for
loop here is blatantly misleading. Use while
instead:
while (! b_valid) {
…
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With