Why won't this code compile?

I'm trying to compile this sample program from AntiRTFM's C++ tutorials and it gives me an error stating that it cannot perform an else statement without a previous if. But the if is there. Please help



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

using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) 
{
	
int theNumber = 76;
int Playersguess = 50;

	if (Playersguess == theNumber)	
		cout << "They are equal";
		cout << endl;
	
	else 
		cout << "Not equal";
		cout << endl;
	
	return 0;
}.
the if statement requires braces if its body is more than two statements long.
1
2
3
4
5
6
if(i==j)
    doSomthing();
else if(i < j)
    doSomthingElse();
else
    giveUp();

Now for more than one statement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if(i==j)
{
    cout << "equal";
    doSomthing();
}
else if(i < j)
{
    cout << "Less"
    doSomthingElse();
}
else
{
    cout << "greater";
    giveUp();
}


Try reading this article.
http://www.cplusplus.com/doc/tutorial/control/
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv)
{

    int theNumber = 76;
    int Playersguess = 50;

    if (Playersguess == theNumber)
    {
         cout << "They are equal";
         cout << endl;
    }

    else
    {
         cout << "Not equal";
         cout << endl;
    }

    return 0;
}


Better:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int main()
{

    const int theNumber = 76;
    const int Playersguess = 50;

    if (Playersguess == theNumber) std::cout << "They are equal" ;
    else std::cout << "Not equal" ;

    std::cout << '\n' ;
}
Thanks for the prompt reply. Now, just to be sure, if there's more than one command I need to enclose

{
like this?
}

Oh, and I'm using Orwell Dev C++ if that's helpful.
You can use any editor you want, syntax won't change. Just read that article on control structures. This website provides great documentation on C++ syntax, reading them would help a lot.
http://www.cplusplus.com/doc/tutorial/control/
Topic archived. No new replies allowed.