【问题标题】:Terminating program if the right input is inserted如果插入了正确的输入,则终止程序
【发布时间】:2021-12-12 20:18:30
【问题描述】:

所以我的问题是,如果插入了正确的输入,例如 A-E(大或小大写字母),我想终止程序,如果他们输入了错误的字母,例如 k、x、L,我想再次问他们这个问题。但我的问题是,即使输入了正确的字母,它也不会停止询问。

#include <iostream>
#include <string>
using namespace std;
int main()
{
char letter;
char grades;
char A, B, C, D, E;
letter = A, B, C, D, E;
do{
cout << "\n Input grade letter: ";
cin >> letter;
if (letter=='A' || letter=='a')
{
    cout << "Your grade is in the range of 96-100";
}else if (letter=='B' || letter=='b')
{
    cout << "Your grade is in the range of 91-95";
}
else if (letter=='C' || letter=='c')
{
    cout << "Your grade is in the range of 86-90";
}
else if (letter=='D'|| letter=='d')
{
    cout << "Your grade is in the range of 80-85";
}
else if (letter=='E'|| letter=='e')
{
    cout << "Your grade is in the range of 79 and below";
}
else {
    cout << "Invalid Input! Try again!";
}
}while(letter==A, B, C, D, E);
///if the input correct
cout<< "\nBye";

return 0;

}

【问题讨论】:

  • 这条线到底应该做什么letter = A, B, C, D, E;?我认为您对变量名和 char 文字之间的区别有一个非常根本的误解。
  • while(字母==A, B, C, D, E);没有做你(可能)期望它做的事情。
  • B C D E 被你的 , 分离评估为真
  • 代码有多个问题但链接的问题不是重复的
  • 我可以用我的代码做什么?

标签: c++ if-statement selection


【解决方案1】:

您的代码存在多个问题:

  1. char A, B, C, D, E; 不会为变量A, B, C, D, E 分配任何值。看来您希望它们将设置为 'A' 'B' ... 'E'

  2. letter = A, B, C, D, E; 不符合您的预期。 letter 只是一个字符,它不能保存多个值。考虑使用更适合您需要的数据结构,尤其是std::set

  3. 同样while(letter==A, B, C, D, E); 不检查字母是否是这些值之一。

【讨论】:

    猜你喜欢
    • 2020-10-09
    • 1970-01-01
    • 2021-09-25
    • 2020-09-19
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多