c++: do while循环出现问题
C++: Having troubles with do while loop
do {
cout << "Enter the account type (C for current and S for savings): ";
cin >> account_type;
} while (account_type != 'S' || 'C');
我有account_type设置为char,问题是,每次我运行程序,我输入S或C循环不断重复。有人能告诉我为什么会这样吗?
c++中所有非零值在布尔运算中计算为true
。所以account_type != 'S' || 'C'
等于account_type != 'S' || true
。这意味着你的循环永远不会退出。
您需要做的是执行两个检查
do {
cout << "Enter the account type (C for current and S for savings): ";
cin >> account_type;
} while (account_type != 'S' && account_type != 'C');
这是因为你不能说'S' || 'C',你会认为c++会认为你的意思是,如果account_type是S或C,然而c++在两个单独的部分中看到这一点:(account_type == 'S') || ('C')
。('C')将默认为true,因此循环将永远循环下去。
你需要写的是:
do {
cout << "Enter the account type (C for current and S for savings): ";
cin >> account_type;
} while (account_type != 'S' && account_type != 'C');
你需要把||改成&&因为如果account_type是S,那么它就不能是C,反之亦然,因此循环永远不会结束。
您的while检查错误。你必须这样写:
while (account_type != 'S' || account_type != 'C')
你不能执行||
检查,或者任何类似的事情,你必须总是重新声明变量
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 在java中解决这段代码时面临循环中的问题
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)
- 退出简单while循环时出现问题
- 循环无限运行C++解决骑士之旅问题
- Visual Studio 2017循环自动向量化问题
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 嵌套While循环不起作用(C++问题)
- 使用 GMP 的 while 循环出现问题
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- OpenMP for 循环并行性问题
- 这个返回元素位置的基于循环的函数有什么问题?
- 为什么循环会导致指针出现问题?
- 使用基于范围的循环迭代矢量时出现问题
- 在 c++ 中循环遍历数组时遇到问题
- 运行无限循环的最小二叉树问题
- 在C++中循环访问自定义结构列表的小问题
- 在 for 循环中更新两个变量时遇到问题C++