在一个简短的基本测试C ++程序中,我使if,else if和else语句似乎不起作用。无论你输入if是什么答案,否则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;
}
答案 0 :(得分:13)
这是因为;
之后的else
:
else;
过早结束陈述,因此下一行与if
条件无关。
你应养成在if
块周围放置花括号的习惯:
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;
}
答案 1 :(得分:2)
在else
之后删除分号。
答案 2 :(得分:1)
您在;
else
删除那样的写作:
else
cout << "Well to be fair I don't care so good day :)." << endl << endl;
此外,您可以使用支架轻松理解..