I feel like I'm missing something obvious...

Alrighty, nothing special here... just trying to figure out what's up with the if statement in the code below. I've looked around, seems like I've formatted it correctly, but I always get an "illegal else without matching if" error along with "Expected a statement". Every instance of someone having this error that I've seen comes from putting a semicolon at the end of the if statement, but it looks like I'm clear on that...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "stdafx.h"
#include <iostream>

int main()

{
	using namespace std;

	cout << "Type a number..." << endl;
	int x;
	cin >> x;
	if (cin.fail())
		cin.clear();
		cout << "That's not a number." << endl;
	else //Errors here- Illegal else without matching if, Intellisense: expected a statement
		using namespace std;
		cout << "You entered " << x << endl;
		cin.clear();
		cin.ignore(1000, '\n');
		cin.get();
	return 0;

}
Last edited on
You need braces{} if you want to encapsulate multiple lines in the if or else.
Only the statement that directly follows the if () is part of the if statement so in your code line 13 is part of the if statement but line 14 is not. If you want multiple statements to be part of the if statement you can use { } to create a compound-statement, like this:
1
2
3
4
5
if (cin.fail())
{
	cin.clear();
	cout << "That's not a number." << endl;
}
Gah I'm such an idiot ._. Thanks to both of you!

Is there any way to stop the else statement from executing even when the if statement is true?
Because this is what appears in the console now.
Type a number...

x
That's not a number.
Type a number...
You entered 0

3
(program ends)
Last edited on
The else statement won't execute if any of the if (or else if) statements are true.
You have use { } on the else too.

programmerdog wrote:
The else statement won't execute if any of the if (or else if) statements are true.

Note that an else if is nothing more than an else clause that contains an else statement.

This
1
2
3
4
5
6
7
8
9
10
11
12
if (a)
{
	// do something
}
else if (b)
{
	// do some other thing
}
else
{
	// do something else
}
is really just the same as this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if (a)
{
	// do something
}
else 
{
	if (b)
	{
		// do some other thing
	}
	else
	{
		// do something else
	}
}

Last edited on
Thanks!
Topic archived. No new replies allowed.