如何在c++中创建一个没有数字的while循环
How to create a while loop in c++ without numbers?
我想写一个c++程序:
- 问"问题吗? (a/b)"
- 从输入 读取字符变量
- 如果变量的值是a,打印"你选择了a!"
- 如果变量的值是b,打印"你选择了b!"
- 在其他情况下,打印"你必须回答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
的值,并确保它是a
或b
。您可以使用while(c != 'a' && c != 'b')
同样,对于if语句,您使用的变量不存在或未初始化。a
、B
、b
没有初始化,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;
}
相关文章:
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何获取一个数字的前3位
- 以C++输出一个数字三角形
- 反转一个数字程序不起作用,为什么?
- 如何让用户在 c++ 中选择一个数字
- 输出一个数字,该数字可能是三种类型之一
- C++在不使用pow或循环的情况下计算一个数字的幂
- 我必须更改我的数字最后一个数字和第一个数字,但不要使用仅带有整数或循环的函数.例如从 12345 到 52341
- 找到所有与自己求和的数字X的快速方法,去掉一个数字得到N
- C++[递归]将一个数字写成2的升序之和
- 试图找到一个数字的平方根,但代码不起作用。C++
- 我没有得到一个数字作为输出,而是一个表情符号
- 我的代码应该接受一个数字,并返回字母等级或"Grade is not valid"但 else 语句不起作用
- 将一个数字拆分为多个数字,每个数字只有一个有效位
- 你怎么编码,如果x不等于一个数字,程序就会退出
- 如何将整数数组相乘得到一个数字?
- 为无符号字符* 分配一个数字
- 如何以更有效的方式检查一个数字是否是素数?
- C++显示两个区间之间的数字的程序检查一个数字是否可以表示为两个素数的总和
- 字符串和双精度的麻烦,等值后再得到一个数字