虽然条件没有得到满足,while ...循环仍然保持循环
我正在写一个简单的RPG游戏控制台游戏,我将开发与图形加班等,但现在我有我的问题。 .. while循环。我不会经常使用它们,但我认为这对于这种必要性是有益的。基本上,我有一个开篇故事,然后给用户4个选项,他们可以通过按下“1”,“2”,“3”或“4”来输入。如果用户输入其他内容,则应显示一条消息,并允许用户键入正确的输入。我的代码如下:虽然条件没有得到满足,while ...循环仍然保持循环
int action; // Used to determine what the user wants to do.
cout << "Story goes here\n\n";
cout << "What would you like to do? (1/2/3/4)\n\n";
cout << "1. Do this\n";
cout << "2. Do that\n";
cout << "3. Do this that\n";
cout << "4. Party\n\n";
cin >> action;
do
{
switch (action)
{
case 1:
cout << "1\n";
break;
case 2:
cout << "2\n";
break;
case 3:
cout << "3\n";
break;
case 4:
cout << "4\n";
break;
default:
cout << "I'm sorry, but I'm not sure what you want to do. Please tell me again using the corresponding number. (1/2/3/4)\n\n";
cin >> action;
break;
}
} while ((action != 1) || (action != 2) || (action != 3) || (action != 4));
system("pause");
现在我测试过,如果我输入5或6,它显示默认的消息,让我再试一次,不过,如果我键入的内容发生了1,2,3,或者4进入交换机并继续输出我打印出来的号码。它永远不会结束。我在MS Visual Studio 2013 Express中使用C++。
我还使用了调试器,它表示动作等于2(或任何我按下的数字),并继续运行循环。我不知道为什么会发生这种情况。
,而不是 “或” 条件try “和” 条件 它能够解决您的问题
变化
while ((action != 1) || (action != 2) || (action != 3) || (action != 4)); // (1)
到
while ((action != 1) && (action != 2) && (action != 3) && (action != 4)); // (2)
分析:
如果action == 1
(1)将计算为
while(false || true || true || true)
=>
while (true)
(2)将计算为
while(false && true && true && true)
=>
while (false)
同时检查'cin >> action'是否成功,否则它将不断使用上次成功输入的值。简单的做法是'while(cin &&(action!= 1)&&'... – 2015-02-09 08:04:00
这很笨拙,因为你基本上必须两次测试条件。 (您的具体问题是布尔测试不正确:您需要&&
而不是||
)。
考虑使用功能,而不是内置的验证:
int getAction(void)
{
for (;;)/*infinite loop idiom*/{
int action; /*scope as local as possible*/
cin >> action;
if (action >=1 || action <= 4){
return action; /*this is ok, so return*/
}
cout << "I'm sorry, but I'm not sure what you want to do. Please tell me again using the corresponding number. (1/2/3/4)\n\n";
}
}
它只是暂停在默认的,因为你所要求的输入和分配的行动。
你应该真的在循环之前初始化动作。一旦行动被分配了1,2,3,4,它将永远循环,因为这就是代码所要做的事情。你再也不会改变它的价值,所以while语句一直在旋转。
在你的case语句中,你需要做任何需要的操作,如果你想退出循环,就在这个时候添加一个退出标志。突破标志着案件陈述的结束,以阻止它进入下一个案例。
您的条件逻辑不正确 - 将所有“||”更改为“&&”。 – 2015-02-09 07:57:35
仔细想想,如果“行动”是“2”,条件将会评估什么。 – juanchopanza 2015-02-09 07:58:58