gpt4 book ai didi

C++ if、else if和else语句问题

转载 作者:太空狗 更新时间:2023-10-29 23:25:28 26 4
gpt4 key购买 nike

在一个简短的基本测试 C++ 程序中,我使 if、else if 和 else 语句似乎不起作用。无论您输入什么答案,if、else if 和 else 语句都会自动直接跳转到 else 语句,我不明白为什么。我尝试了许多不同类型的方法来消除此错误,但似乎都不起作用

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

int main()
{
string name;
string feeling;
int age;

//IMPORTANT MESSAGE
cout << "THIS PROGRAM IS CAPS/SLANG SENSITIVE!" << endl << endl;
//IMPORTANT MESSAGE

cout << "Hello User, please enter name: ";
cin >> name;
cout << endl << endl;

cout << "Now please enter your age: ";
cin >> age;
cout << endl << endl;

cout << "Hello " << name << ", you are " << age << " years old." << endl << endl;
system("pause");
cout << endl;

cout << "How are you today " << name << "?: ";
cin >> feeling;
cout << endl << endl;

if (feeling == "Good")
cout << "That's great!";

else if (feeling == "Okay")
cout << "Fair enough.";

else;
cout << "Well to be fair I don't care so good day :)." << endl << endl;

cin.get();
return 0;

最佳答案

是因为;else之后:

else;

语句结束得太早,所以下一行与 if 条件无关。

您应该养成在 if block 周围放置大括号的习惯:

if (feeling == "Good") {
cout << "That's great!";
} else if (feeling == "Okay") {
cout << "Fair enough.";
} else {
cout << "Well to be fair I don't care so good day :)." << endl << endl;
}

关于C++ if、else if和else语句问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24961508/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com