Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ if, else if and else statement problems

In a short and basic testing C++ program I made the if, else if and else statement do not appear to be working. Regardless of what answer you input the if, else if and else statement just auto jumps straight to the else statement and I don't understand why. I have tried many different types of methods to remove this error but none appear to work

#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;

}

like image 538
zTBxN Avatar asked Sep 26 '26 06:09

zTBxN


2 Answers

It's because of the ; after the else:

else;

That ends the statement too early, so the next line has nothing to do with the if conditions.

You should get into the habit of putting curly braces around your if blocks:

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;
}
like image 89
Joseph Mansfield Avatar answered Sep 27 '26 19:09

Joseph Mansfield


Remove the semi-colon after else.

like image 26
Yelneerg Avatar answered Sep 27 '26 18:09

Yelneerg