而循环在第二个用户输入C++后停止工作
while loop stops working after second user input C++
我正在尝试在我的程序中实现一个功能,上面写着"你想退出吗?如果"Y"或"y"退出程序。如果"N"或"n"重新运行菜单,让用户做任何他们想做的事情。
我面临的问题是我的菜单第一次运行,用户可以说是或否。然后第二次他们可以说是或否。然而,当它第三次到达while循环时,它会无限输出菜单。
任何人都可以提供建议吗?
菜单的代码是
char exitInput = NULL;
char Y = 'Y', y = 'y', N = 'N', n = 'n';
while (exitInput != Y || exitInput != y || exitInput == N || exitInput == n)
{
cout << "*t Please choose one of the following options. t *" << endl;
cout << "1. t" << "Transfer an amount n"
<< "2. t" << "List recent transactions n"
<< "3. t" << "Display account details and current balance n"
<< "4. t" << "Quit n";
int menuSelection;
cout << "Enter your option here: ";
cin >> menuSelection;
switch (menuSelection)
{
case 1:
.......
case 2:
cout << "Do you want to exit the application? ";
cin >> exitInput;
}
}
此条件
while (exitInput != Y || exitInput != y || exitInput == N || exitInput == n)
永远都是真的。您必须将其更改为以下内容:
while (exitInput != Y && exitInput != y)
另外,exitInput
的初始值没有多大意义,只需char exitInput = 'n'
我不确定我是否很好地理解了您的问题,但如果它是"当我说'是'时,菜单又回来了",这是正常的。 exitInput 不能同时等于 Y 和 y,因此 while 条件始终为真。
你应该尝试:
while ((exitInput != Y && exitInput != y) || exitInput == N || exitInput == n)
编辑
我可以在一个简单的 win32 应用程序中看到您的错误。我已经通过将menuselection
的类型从 int
更改为 char
来解决它,但我不知道为什么它有时适用于整数。这是我的测试程序:
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
char exitInput = 'n';
char menuSelection;
while (exitInput !='Y' && exitInput !='y')
{
cout << "*t Please choose one of the following options. t *" << endl;
cout << "1. t" << "Transfer an amount " << endl
<< "2. t" << "List recent transactions " << endl
<< "3. t" << "Display account details and current balance " << endl
<< "4. t" << "Quit " << endl;
cout << "Enter your option here: ";
cin >> menuSelection;
switch (menuSelection)
{
case '2':
cout << "Do you want to exit the application? ";
cin >> exitInput;
break;
default:
cout << "Command is : " << menuSelection << endl;
cout << "Command not found !" << endl;
break;
}
}
return 0;
}
编辑 2
我找到了这个线程,其中解释了问题。 测试了,问题消失了。为什么我们会打电话给 cin-clear-and-cin-ign-ign-ignore-after-read-input
只需将 while 循环中的条件更改为:
while ((exitInput != Y) && (exitInput != y))
它将按预期工作。你的原始条件总是正确的,无论exitInput有什么值 - 这就是你编程失败的原因。请注意,无需检查 exitInput 是否为 n/N。y/Y 表示退出,任何其他输入表示不退出,因此您实际上只需要检查 y/Y。
在 while() 检查中的比较中有一个错误。尝试这样的事情:
while (exitInput != Y && exitInput != y )
{
cout << "*t Please choose one of the following options. t *" << endl;
...
我还可以评论其他事情,但它们没有解决您的问题。呵呵
- Visual Studio 2017 停止工作,并在打开后显示许多控制台窗口
- 自 Windows 10 20H1 以来,具有单独线程的多个窗口停止工作
- C++代码停止工作错误使用cout内部函数
- LoadImage 在 Windows 更新后停止工作
- C++程序工作,但 Windows 显示"程序.exe已停止工作"
- VS 代码 C/C++ 智能感知在更新后停止工作
- 不使用与左右停止工作命名空间 std 的简单比较
- 为什么通过定义另一个指针单元格,整个代码停止工作?
- 德拉吉诺 LG01-S 收到异常数据包并停止工作
- G++ 在生成文件中使用时停止工作
- 当循环在条件C++之前停止工作时
- GCC:--静态链接到pthread的整个存档配方在最近的GCC版本中停止工作
- 正则表达式代码无缘无故停止工作
- 我的代码在第 4 个选择后停止工作
- 读取二进制文件大小的短自上周以来停止工作
- C++ 已停止工作静态映射函数
- Vscode 自动格式化代码在运行几次后停止工作
- 程序 使用链表插入数据时停止工作
- 当我尝试输入时程序停止工作
- C++参数化构造函数使代码在传递大输入时停止工作