我在代码中循环时遇到了问题。我设置了条件以在输入 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);