菜单中的C 循环
C++ Loop in menu
在我的代码中,即使我输入'q'或'q',程序也会继续循环菜单。这里怎么了?这是代码:
{
char selection;
do {
cout << "Add a county election file A" << endl;
cout << "Show election totals on screen P" << endl;
cout << "Search for county results S" << endl;
cout << "Exit the program Q" << endl;
cout << "Please enter your choice: ";
cin >> selection;
} while ((selection != 'Q' || selection != 'q'));
return 0;
}
您要在测试中使用和(&&
)操作员,而不是OR(||
)操作员。否则,selection != 'Q'
和selection != 'q'
之一将永远是正确的,您的循环永远不会退出。
正如指出的那样,||
无法满足您的要求。您需要使用&&
操作员。
如果按q
,这就是情况。
(selection != 'Q' || selection != 'q')
|---------------| |--------------|
true false
如果按Q
,那就是情况。
(selection != 'Q' || selection != 'q')
|---------------| |--------------|
false true
循环应该是这样的。
while((selection != 'Q' && selection != 'q'));
尝试一下:
} while((selection != 'Q' && selection != 'q'));
使用toupper()
。
如果执行此操作,while ( toupper(selection) != 'Q' )
您将不需要检查上部和下情况。
#include <iostream>
#include <stdio.h>
using namespace std;
int main(void)
{
char selection;
do {
cout << "The Menu" << endl;
cout << "____________________________________" << endl;
cout << "Add a county election file A" << endl;
cout << "Show election totals on screen P" << endl;
cout << "Search for county results S" << endl;
cout << "Exit the program Q" << endl;
cout << "____________________________________" << endl;
cout << "Please enter your choice: ";
cin >> selection;
} while ( toupper(selection) != 'Q' );
cout<<" nPress any key to continuen";
cin.ignore();
cin.get();
return 0;
}
相关文章:
- 我正在尝试创建一个菜单,但我的代码一直在循环
- 从子菜单返回后,正确的输入至少进入验证循环一次
- C++ 我的开关格式中的循环不允许我显示菜单选项或接受输入?
- C++循环菜单时做
- 为什么我的 Do-while 循环无法在C++中运行菜单
- 我正在尝试用 c++ 制作菜单,但不明白为什么它不循环
- 我的期末考试遇到了麻烦.代码不断循环回到我的订购菜单,不会显示我的总价
- 试图调节我的 do-while 以停止在终端中退出程序.菜单不会根据需要循环使用当前语句
- 菜单驱动的逻辑错误导致无限循环
- 我的开关菜单在一段时间循环中出现问题
- 为菜单创建基本的用户输入验证(使用基本的 while/do-while 等循环)
- 菜单驱动器输入DO循环
- C++切换语句循环回菜单
- 为项目和循环创建简单的控制菜单会比预期打印提示的次数更多
- 基本菜单驱动程序C ,无限循环
- (C++)如何让它循环回到菜单?计算器类型
- 菜单结构和循环
- 菜单中的C 循环
- C++:循环菜单开关
- C++循环菜单