我在代码中最后一次执行while循环时遇到问题。我有条件设置为在输入Y,N,y或n时停止外观,但即使输入了这些值,循环仍继续运行并继续询问Y或N.在调试中,似乎Ascii值为字符也存储在变量中?当输入这4个字符中的任何一个时,我需要更改do do loop end吗?
#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');
答案 0 :(得分:3)
您的循环结束条件错误:
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
答案 1 :(得分:2)
您需要使用&&
而不是||
:
} while (filled != 'Y' && filled != 'N' && filled != 'y' && filled != 'n');
答案 2 :(得分:0)
如果按照你的说法写下它,也许它会更清楚,并有助于避免这些错误:
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);