RIDDLEisVoltron
RIDDLEisVoltron

Reputation: 41

Why is my while loop getting skipped?

The program skips over my while loops and ends. Super frustrating. I even put the value of AnsCheck to false right before the while loop. No luck. The program does none of what is in the While loop. Here's the relevant code:

bool AnsCheck;
AnsCheck = false;
while (AnsCheck = false)
{
    getline(cin, Ans1);
    if (Ans1 != "T" || Ans1 != "F")
    {
        cout << "Please Enter T for true or F for False" << endl;
        cout << "answer not T or not F" << endl; // debugging
    }
    else
    {
        AnsCheck = true;
        cout << "changed bool to true" << endl;
    }
}

Upvotes: 0

Views: 1140

Answers (3)

Omar Moodie
Omar Moodie

Reputation: 290

Like the others have already stated, using the comparison operator "==" instead of telling the compiler you're assigning by using "=" and you should be fine.

Change this:

while (AnsCheck = false)

To this:

while (AnsCheck == false)

Hopefully this helps. Cheers!

Upvotes: 0

2785528
2785528

Reputation: 5566

(AnsCheck = false)


You need to write this comparison in the other order, so that the compiler can generate an error.

(false = AnsCheck)

It is a difficult transition to learn. Check your coding standard.

Upvotes: 0

ndmeiri
ndmeiri

Reputation: 5029

You need to use the comparison operator for equality == instead of the assignment operator =.

while (AnsCheck == false) {
    // ...
}

Also, as you mentioned in a comment below this answer, the condition in your if statement is never being evaluated as true. To compare strings, you should use strcmp, which returns 0 when the contents of both c-strings are equal. See this reference for more information.

if (strcmp(Ans1, "T") != 0 && strcmp(Ans1, "F") != 0) {
    // ...
}

Upvotes: 6

Related Questions