Problem regardind else

I'm having trouble because when i try to compile i get this comment : error: ‘else’ without a previous ‘if’
I think its something related to the { } but not so sure now.... any help appreciated
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
27
28
29
30
31
32
33
34
int main()
{
cout << "Please enter your name : " << endl;
string name;
cin >> name;
	const string greeting = "Hello, " +name+ " !";

const int pad = 1;
const int rows = pad * 2 + 3;
const string::size_type cols = greeting.size() + pad * 2 + 2;

cout << endl;

for (int r = 0; r != rows; ++r) {

string::size_type c = 0;

while (c != cols) {

 if (r == pad +1 && c == pad +1)
cout << greeting;
c += greeting.size(); 
 
} else { 

if (r == 0 || r == rows -1 || c == 0 || c == cols -1)
cout << "*"; 
else 
cout << " ";
++c; }}
cout << endl; 
}
return 0;
}

Pair up every opening { with it's closing }. You will find where is the one misplaced. Also, until you're not fully comfortable with the syntax, don't omit the {} (as you do at the if statement on line 20).
will try and let you know, but first need to read a bit more on what and how the { } should be used cause i think i misunderstood something.....
anyway thanks
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
27
28
29
30
31
32
33
34
35
36
int main()
{
cout << "Please enter your name : " << endl;
string name;
cin >> name;

const string greeting = "Hello, " +name+ " !";
const int pad = 1;
const int rows = pad * 2 + 3;
const string::size_type cols = greeting.size() + pad * 2 + 2;

cout << endl;

for (int r = 0; r != rows; ++r)
{
    string::size_type c = 0;

    while (c != cols)
    {
        if (r == pad +1 && c == pad +1)
            cout << greeting;
        c += greeting.size(); 
    }
    else
    { 
        if (r == 0 || r == rows -1 || c == 0 || c == cols -1)
            cout << "*"; 
        else 
            cout << " ";
    ++c;
    }
}
cout << endl; 
} // This is not proper usage, you have not opened all that you try to close.
return 0;
}


The proper usage of brackets with if and else is as follows:
1
2
3
4
5
6
7
8
if (expression)
{
    // execute your statements here
}
else
{
    // execute your statements here
}
Of course, the spacing is free to change to your liking.
never underestimate the value of proper indentation, and code clarity.

Just because you can do this: ++c; }}, doesn't mean you should.
Tried setting and reviewing the program but still cant get rid of the error... Does anyone know a good source to learn more about {}
closed account (Lv0f92yv)
If you're confused as to why some examples don't use braces:

You don't need braces if you are only executing a single statement inside an if or else clause.

Otherwise, you need braces:

1
2
3
4
5
if ( a == 3 )
{
   a++;
   cout << a << "\n";
}


1
2
if ( a == 3 )
  a++;


1
2
3
4
if ( a == 3 )
{
  a++;
}


All are acceptable.
Topic archived. No new replies allowed.