While循环不断重复
我设置了一个 while 循环,我想选择 r 或 h,我不想使用 for 循环,但我想使用开关,为什么当我输入 r 或 h 时,它会不断重复这种情况下的 cout 一百万次?我不能只说一次..
while (chooseMove == 'r' or 'h')
{
switch (chooseMove)
{
case 'r':
cout << "you chose r";
break;
case 'h':
cout << "you chose h";
break;
}
}
我也用forloops尝试过,并且遇到了同样的问题,我无法弄清楚
I setup a while loop where i want to choose 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您的意思是
while (chooseMove == 'r' 或 choiceMove == 'h')
。您当前编写的内容相当于((chooseMove == 'r') or ('h'))
,并且'h'
的计算结果为true
。也许您还在寻求有关输入逻辑的帮助:
如果输入流关闭,这也会终止,您可以使用
success
检查操作是否成功。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 astrue
.Maybe you were also asking for help with the input logic:
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.
这是一个问题:
试试这个:
当你写的时候(它是如何编译的?
or
不是C++):它被解释为:
语句
'h'
始终为 true,因此while
循环将永远运行。This is a problem:
Try this instead:
When you write (how did this even compile?
or
isn't C++):It is interpreted as:
The statement
'h'
is always true, so thewhile
loop runs forever.chooseMove == 'r' 或 'h'
是什么意思?根据C++标准,这被分组为
(chooseMove == 'r') 或 ('h')
;这将
'h'
隐式转换为bool
会产生(chooseMove ==
。第二个条件永远为真。'r')或('h'!= 0)
What does
chooseMove == 'r' or 'h'
mean? According to the C++standard, this is grouped as
(chooseMove == 'r') or ('h')
; theimplicit conversion of
'h'
tobool
then results in(chooseMove ==
. The second condition will always be true.'r') or ('h' != 0)
这相当于:
所以这是无限循环。请注意,
or
和||
是同一件事。你想要的是这样的:
which is equivalent to this:
So this is infinite loop. Note that
or
and||
are same thing.What you want is this: