if/else 语句输出由于加号或减号而未显示正确的消息

if/else statement output not displaying correct message because of plus or minus sign

本文关键字:显示 消息 语句 else 输出 于加号 if      更新时间:2023-10-16

我有一个作业,我们必须展示字母成绩。没有加号或减号的数据类型不会给出正确的值。值"A"正确输出,但"A-"不能。代码如下:

#include <iostream>
using namespace std;
int main()
{
char letGrade;
cout << "What is your letter grade? ";
cin >> letGrade;
if (letGrade == 'A')
cout << "The numeric value is 4.0n";
else if (letGrade == 'A-')
cout << "The numeric value is 3.5n";
cout << "That's an invalid numeric value.n";
return 0;
}

在输入中是A-,行

cin >> letGrade;

不会读取-部分以letGrade.它将只读取A部分。

letGrade更改为std::string。此外,将比较语句更改为字符串。

std::string letGrade;
cout << "What is your letter grade? ";
cin >> letGrade;
if (letGrade == "A")
cout << "The numeric value is 4.0n";
else if (letGrade == "A-")
cout << "The numeric value is 3.5n";

您可以使用getLine(string)来读取string,因为"A-"有两个字符。请记住,char只能容纳一个字符,您可以使用char数组,但string更简单。这是使用getLine的示例。

  1. istream& getline (istream& is, string& str, char delim);

  2. istream& getline (istream& is, string& str);

GetLineis中提取字符并将其存储到str中,直到找到分隔字符delim(或 (2( 的换行符""(。

// extract to string
#include <iostream>
#include <string>
int main ()
{
std::string name;
std::cout << "Please, enter your full name: ";
std::getline (std::cin,name);
std::cout << "Hello, " << name << "!n";
return 0;
}

因此,您的代码将是:

#include <iostream>
using namespace std;
int main()
{
std::string letGrade;
cout << "What is your letter grade? ";
std::getline (std::cin,letGrade);
if (letGrade == "A")
cout << "The numeric value is 4.0n";
else if (letGrade == "A-")
cout << "The numeric value is 3.5n";
else
cout << "That's an invalid numeric value.n";
return 0;
}

仅添加所需的else if。测试一下!