Error C2181: illegal else without matching if.

I'm making a number guessing game program and I keep getting the error: C2181: illegal else without matching if.
I'm guessing you have an else statement that doesn't have an if statement immediately before it.
Looks like you need an if to match that else ;-)

Hard to help without more info.

Edit: note to self - refresh before posting.
Last edited on
I got it to work but now it doesn't do the calculations I inputted. Here is my script... The calculations are in the else if statements...

#include <iostream>

using namespace std;

int main()

{
int secretnumber = 77;
int num, num2, guessattempts=1-10;

//Greeting to the user
cout <<"\t\t\tWelcome to the guessing game!\n";
cout <<"\t\t\t_____________________________\n";

//Directions for the user
cout <<"Directions: ";
cout <<"You will have a total of 10 guesses to figure\n";
cout <<"\t what is the secret number.\n";
cout <<"\t The secret number lies between 1 to 100.\n\n";

//User input
cout <<"\t Please enter your chosen number.\n\t ";
cin >> num;


if ((num <=0 || num > 100))

{
cout <<"\t Please enter a number from 1 to 100.\n\n";

}

else if ( (num <1 && num >77) )

{
num2 = num - secretnumber;

cout <<"\t You are " << num2 <<"away from the secret number.\n";
cout <<"\t Try again.\n";
cout <<"\t You have " <<guessattempts<<" guess attempts remaining.\n";

}

else if ((num <77 && num >100))

{
num2 = num + secretnumber;

cout <<"\t You are " << num2 <<" away from the secret number.\n";
cout <<"\t Try again.\n\n";
cout <<"\t You have " <<guessattempts<<" guess attempts remaining.\n";
}

else if (num == 77)

{
cout <<"\t You guessed the right number! Congrats!";

}


return 0;
}
Please use code tags. It makes your code easier to read and allows one to reference code by line number.

You need a loop (for or while) e.g.:
1
2
3
4
5
6
7
8
9
10
int guessattemps=0;
while(guessattemps < 10){
... //code

else if(num == 77){
	cout << ...
	break;
}
++guessattempts;
}


Neither of these statements will ever be true:
1
2
3
if((num < 1 && num > 77))
...
else if ((num <77 && num >100))

You have already checked the entry above so there is no need for the "num<1" and "num>100".
Okay so I do that for all the else if inside the while?
Topic archived. No new replies allowed.