if/else 语句输出由于加号或减号而未显示正确的消息
if/else statement output not displaying correct message because of plus or minus sign
我有一个作业,我们必须展示字母成绩。没有加号或减号的数据类型不会给出正确的值。值"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
的示例。
istream& getline (istream& is, string& str, char delim);
istream& getline (istream& is, string& str);
GetLine
从is
中提取字符并将其存储到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
。测试一下!
相关文章:
- SDL 映像:无法打开映像,仅显示错误消息
- if/else 语句输出由于加号或减号而未显示正确的消息
- C++MSVC-显示未捕获的异常消息
- 大多数代码不仅显示欢迎消息和"enter pin"?
- C++/CLI 项目如何在控制台窗口中显示消息
- git_remote_fetch返回错误并显示消息:"there is no TLS stream available"
- c++ HMENU 显示消息框
- 显示消息而不是用户的输入
- 包含文本和整数组件的显示消息
- 如何只插入数字和字母应该显示消息或其他内容
- 在发送信号的终端中显示消息
- 为什么我的MFC应用程序在打开/运行时也不显示消息就被卸载了
- 单击"菜单"时显示消息框未显示在屏幕上
- 我想在应用程序因内存耗尽而崩溃时显示消息框
- 显示消息框后,子窗口失去焦点
- 仅显示消息窗口中的电源状态更改通知
- 如何在QT中显示消息框中的图标
- 程序崩溃并显示消息"terminate called recursively"而不引发任何异常
- 在OpenGL屏幕中显示消息在Windows上不起作用
- MFC 对话框后不显示消息框