字符在循环条件下执行
Chars in do while loop conditions
我在代码中循环时遇到了问题。我设置了条件以在输入 Y、N、y 或 n 时停止查找,但即使输入了这些值,循环也会继续运行并继续请求 Y 或 N。在调试中,字符的 Ascii 值似乎也存储在变量中?当输入这 4 个字符中的任何一个时,我需要更改什么才能让 do while 循环结束?
#include <string>
#include <iostream>
#include <iomanip>``
using namespace std;
int main()
{
int numberOfShapes, i, j, k, rectangleBase, rectangleHeight;
char star = '*';
char filled;
do
{
cout << "Enter the integer between 6 and 20 that you would like to be the base of the rectangle: ";
cin >> rectangleBase;
}while (rectangleBase < 6 || rectangleBase > 20);
rectangleHeight = rectangleBase / 2;
do
{
cout << "Enter the number of shapes you would like to draw(Greater than 0 and less than or equal to 10: ";
cin >> numberOfShapes;
} while (numberOfShapes <= 0 || numberOfShapes > 10);
do
{
cout << "Would you like a filled shape? [Y or N]: ";
cin >> filled;
} while (filled != 'Y' || filled != 'N' || filled != 'y' || filled != 'n');
您的循环结束条件是错误的:
while (filled != 'Y' || filled != 'N' || filled != 'y' || filled != 'n');
考虑到该值是'y'
则您的条件将是:
(true || true || false || true)
其计算结果为 true
.
更改为:
while (filled != 'Y' && filled != 'N' && filled != 'y' && filled != 'n');
然后它将是:
-> 'y' (true && true && false && true) -> false
-> 'l' (true && true && true && true) -> true
你需要使用&&
而不是||
:
} while (filled != 'Y' && filled != 'N' && filled != 'y' && filled != 'n');
如果你按照你说的写它,也许它会更清楚,并有助于避免这些错误:
do
{
cout << "Would you like a filled shape? [Y or N]: ";
cin >> filled;
if (filled == 'Y' || filled == 'N' || filled == 'y' || filled == 'n')
break;
}
while (true);
相关文章:
- 为什么简单的算术减法在"if"条件下不起作用?
- 在什么条件下使用 std::memcpy 在对象之间复制是安全的?
- 改进简单条件下C++样式
- 唤醒多个线程以在每个条件下工作一次
- "is defined"宏检查及其调用必须处于不同的条件下吗?
- 在if条件下,右或左改变值的相等性检查是否有任何区别
- C++代码在 for 循环的条件下给出运行时错误,而如果它被具有相同意义的代码替换,则编译正确
- 在 constexpr-if 条件下比较 constexpr 函数参数会导致错误
- 轮班操作在条件下使用的说明
- 如何在 Linux 上强制执行矢量下标超出范围的调试断言
- 在不同条件下无法访问我的向量变量
- 在某些条件下最大化 GCD
- 为什么在执行条件变量通知之前我们需要一个空的 std::lock_guard?
- 如何更改此空隙函数,以便在特殊条件下返回一个生成的字符串
- 在if-Statement条件下与分配有关的错误
- 如何正确使用“ sizeof”操作员在循环的条件下正确使用
- 提升::MSM 检查保护条件下的状态转换
- 字符在循环条件下执行
- 在什么条件下,数据库在从 cpp 执行选择查询时不会关闭游标
- C++在两个不同的条件下执行/while循环