我在处理代码中的最后一个 do while 循环时遇到问题。我设置了在输入 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
关于c++ - do while 循环条件中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46937584/