如何在c++中创建一个没有数字的while循环

How to create a while loop in c++ without numbers?

本文关键字:一个 数字 循环 while c++ 创建      更新时间:2023-10-16

我想写一个c++程序:

  1. 问"问题吗? (a/b)"
  2. 从输入
  3. 读取字符变量
  4. 如果变量的值是a,打印"你选择了a!"
  5. 如果变量的值是b,打印"你选择了b!"
  6. 在其他情况下,打印"你必须回答a或b",并从第一个问题开始。
我写的

:

    #include <iostream>
    using namespace std;
    main()
    {
       char c = A, a, b, B;
       cout << "Question?(a/b)" << endl;
       cin >> c;
       while ("You must answer a or b") {
           cin >> c;
       }
       if ( c = A || a )
           cout << "You chose a!" << endl;
       if ( c = B || b )
           cout << "You chose b!" << endl;
   }

我知道有"if"的部分是完全错误的,但我不明白如何做…

字符串"You must answer a or b"的真值永远不变。您要检查的是c的值,并确保它是ab。您可以使用while(c != 'a' && c != 'b')

来完成此操作。

同样,对于if语句,您使用的变量不存在或未初始化。aBb没有初始化,A不存在。不管怎样,你都不需要它们。

另外,||操作符不能这样工作。每边都需要一个真值。因此,您应该执行以下操作:if(c == 'a' || c == 'b')

下面的代码可能会对您有所帮助:

#include <iostream>
using namespace std;

int main()
{
    char c;
    do {
        cout << "Choose 'a' or 'b' (to quit enter 'q'):" << endl;
        cin >> c;
        if ((c == 'a') || (c == 'b'))
        {
            cout << "You chose " << c << endl;
        }
    } while (c != 'q');
    return 0;
}