while loop issue

Why didn't this work? It leaves me stuck in the loop. Can't I use or || in a while loop?

1
2
3
4
5
6
  while (userInput != "y" || userInput != "n")
	{
		cout << "" << endl;
		cout << "Would you like to preview message before send? (y/n) " << endl;
		cin >> userInput;
	}
 
while (userInput != "y" || userInput != "n")


Code above is waiting for inputs "y" OR "n" and nothing else. Giving inputs anything else will free the loop to continuing the program

Last edited on
If I type y or n it stays in the loop. It won't continue. I think it should but if I write it like while (userInput != "y") I can press y and the program goes on.
The condition is always true regardless of what you enter.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

using namespace std;

int main()
{
  string userInput;
  userInput = "y";
  while (userInput == "y")
	{
		cout << "" << endl;
		cout << "Would you like to preview message before send? (y/n) " << endl;
		cin >> userInput;
	}
    return 0;
}

Truth table for:

1
2
3
4
5
6
7
8
Truth table for: 

while (userInput != "y" || userInput != "n")

user        | result  | Stay in while loop?
"y"         | 1       | yes since userInput != "y" OR userInput != "n"
"n"         | 1       | yes since userInput != "y" OR userInput != "n"
anything else | 1       |yes since "anything else" is not "y" OR "n"
Last edited on
OK so how else could I write this to accept y or n for the question and if anything else is entered then it loops?
I know that a while loops until the statement is false. So != "y" is true until you type "y" then its false. My problem is the || operator. It made it loop no matter what the input is.
Have you considered && ? If it is not y AND it is not n then iterate. Hence anything other than y and n.
jsonlickliter wrote: " So != "y" is true until you type "y" then its false."

reply:

Notice that the the condition (userInput != "y" || userInput != "n") always prints 1 for TRUE regardless of what you enter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

using namespace std;

int main()
{
  string userInput;
  userInput = "y";
  while (userInput != "y" || userInput != "n")
	{
		cout << "" << endl;
		cout << "Would you like to preview message before send? (y/n) " << endl;
		cin >> userInput;
                cout << (userInput != "y") << endl;             // value of P
                cout << (userInput !=" n") << endl;             //  value of Q
                cout << (userInput != "y" || userInput != "n") << endl;  // this is the condition P OR Q
	}
    return 0;
}

Last edited on
OK the && worked. Thanks. This != || crap was driving me nuts.
Well if you think about it, it will always not be equal to at least one of them :P but it will not always be not equal to both of them.
Yeah that's confusing to me. Thanks for posting.
Topic archived. No new replies allowed.