While loop keeps repeating
I setup a while loop where i want to 开发者_如何学Gochoose r or h, i dont want to use forloops but i want to use a switch why is it when i enter r or h it keeps repeating a million times the cout for that case? I cant get it to just say it once..
while (chooseMove == 'r' or 'h')
{
switch (chooseMove)
{
case 'r':
cout << "you chose r";
break;
case 'h':
cout << "you chose h";
break;
}
}
I also tried it with forloops and had the same problem i cant figure it out
What you mean is while (chooseMove == 'r' or chooseMove == 'h')
. What you've currently written is equivalent to ((chooseMove == 'r') or ('h'))
, and 'h'
evaluates as true
.
Maybe you were also asking for help with the input logic:
char c;
bool success = false;
while (std::in >> c)
{
switch(c) {
case 'r': /* ... */ success = true; break;
case 'h': /* ... */ success = true; break;
}
if (success) break;
}
This will also terminate if the input stream is closed, and you can use success
to inspect the success of the operation.
Because that's what you programmed it to do.
If you want the loop to stop or pause (and say, wait for input), you should add that code into the loop.
while (chooseMove == 'r' or chooseMove == 'h')
{
switch (chooseMove)
{
case 'r':
cout << "you chose r";
break;
case 'h':
cout << "you chose h";
break;
}
std::cin >> chooseMove; //stop and wait for more input
}
This is a problem:
while (chooseMove == 'r' or 'h')
Try this instead:
while ((chooseMove == 'r') || (chooseMove == 'h'))
When you write (how did this even compile? or
isn't C++):
chooseMove == 'r' or 'h'
It is interpreted as:
(chooseMove == 'r') or ('h')
The statement 'h'
is always true, so the while
loop runs forever.
What does chooseMove == 'r' or 'h'
mean? According to the C++
standard, this is grouped as (chooseMove == 'r') or ('h')
; the
implicit conversion of 'h'
to bool
then results in (chooseMove ==
'r') or ('h' != 0)
. The second condition will always be true.
while (chooseMove == 'r' or 'h')
which is equivalent to this:
while ( (chooseMove == 'r') or true)
//same as while ( (chooseMove == 'r') || true)
So this is infinite loop. Note that or
and ||
are same thing.
What you want is this:
while ( (chooseMove == 'r') or (chooseMove == 'h'))
//same as while ( (chooseMove == 'r') || (chooseMove == 'h'))
精彩评论