Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this simple logic doesn't work?

Tags:

c++

I just couldn't figure out of why this simple logic in while loop doesn't work.

Basically what the function does is that, it takes an argument and will check in the while loop to see whether if it is not "yes" or "no" then keep looping.

void getAnswer(string answer) {

    string newAnswer = "";
    newAnswer = answer;
    while (newAnswer != "Yes" || newAnswer != "yes" || newAnswer != "Y" || newAnswer != "y" || newAnswer != "No" || newAnswer != "no") {
            cout << "Enter yes or no.." << endl;
            cin >> newAnswer;

        }

        if (newAnswer == "Yes" || newAnswer == "yes" || newAnswer == "Y" || newAnswer == "y") {
            chooseOptions();
        } else {
            cout << "Bye See you again " << endl;
            exit(1);
        } 
}

But even though I enter "yes" or "no" , it will still looping.

like image 601
airsoftFreak Avatar asked Jun 24 '15 07:06

airsoftFreak


2 Answers

De Morgan's laws state that:

"not (A and B)" is the same as "(not A) or (not B)"

Applying this law on your on your condition:

newAnswer != "Yes" || newAnswer != "yes" || ...

!(newAnswer == "Yes" && newAnswer == "yes" && ...)

Now it's easier to see why it's wrong.

If newAnswer is something that is not "Yes" or "yes", it'll be evaluated to true, and that's not what you want.

The solution would be changing || to &&.

like image 125
Maroun Avatar answered Oct 01 '22 06:10

Maroun


Think about it. I ask you a yes or no question. You tell me "no".

I go down my list, and stop as SOON as I get to a true statement, because that's what logical OR means.

newAnswer != "Yes" >> true. Done. Continue looping.

Fine, you say. This time, you answer "Yes".

newAnswer != "Yes" >> false

newAnswer != "anything else" >> true. Done. Continue looping.

This is a tautology. It's not possible to make that OR condition false. You should use AND.

In your own words, it's not "while not yes or no" but "while not yes AND not no AND not n AND not y..."

like image 45
Ron Thompson Avatar answered Oct 01 '22 07:10

Ron Thompson