c++ - do while 循环条件中的字符

标签 c++ char do-while

我在处理代码中的最后一个 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/

相关文章:

c - 将字符串传递给 init 函数并将其存储在 malloc 结构中

c - do while循环中的fprintf只在文件C中写入一行

c++ - do{}while(0) 有什么用?

更改 char 指针数组中的字符串

c++ - 我的字符计数代码是字符计数错误。为什么?

c++ - while 循环不能有两个 cin 语句吗?

c++ - 为什么存在 shared_ptr 的原子重载

c++ - 如何刷新图形避免黑屏?

c++ - 根据静态/非静态组织加载/保存功能的最佳方式

C++ stringstream : Extracting consistently, 不管字符串是否以空格结尾?