If and Else Statements

Hello. I'm new to this forum, and also C++, which I just started learning on Saturday, self-taught. I have been playing around with it a little bit, and I tried to make a simple program that:

Asks your name;
Says nice to meet you;
Then you press "f" and it will close the program, but will revert back to the continue question if another button is pressed.

I have played with it for a half hour or so, and, logically thinking, I thought an if-else statement would work. Now it gives me an error, telling me it expects a primary expression and a ";" before else.

Code:

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
#include <iostream>
#include <windows.h>
using namespace std;

int main()
{
    {
    cout << "What is your name, friend? ";
    string name;
    cin >> name;
    cout << "Well, it is good to meet you, " << name << ".";
    }
    
    Sleep (2000);

    char exit;
    {
         cout << "Press 'f' to continue. : ";
         cin >> exit;
    }
    
    if (exit == 'f');
    Sleep (500);
    
    else
    {
        goto << exit;
    }
    return 0;
}


I realize it may be messy, illogical looking, or what not, but it is my first attempt without any tutorials, and I am going off the extremely small knowledge I have of the language. Any help is appreciated, and I look forward to learning more about this language as time goes on!

Thanks!

~Jon
This is becuse you have placed a ; after if statment:
1
2
if(exit=='f');      //<-- remove this ;
Sleep(500);


What happens with this ; is that the if block is treated like this:
1
2
if(exit=='f')
;              //<-- its is treated as a blank statment 


So the if block ends at ; and then you have sleep statement which is outside of if block since you have not used braces. Without braces scope of if block is only upto the immediate following statment. So sleep is outside if block. And when control reaches else block it asks you for an if block because else must be preceeded by valid if block. And in this case it is not. Makes sense?

Let me know if you need further explanation.

Last edited on
It works exactly as supposed to! Thanks! And yeah, after reading over it, I understand what you mean, and it all makes sense. Thank you again!

Also, is there are way to make it automatically press a key after you press f? Like, if you press 'f', there is no need to press enter afterwards, because it is already done.

Edit: Whoops! Forgot to test the else function! It doesn't matter what key I press, it will always exit. Any suggestions?
Last edited on
Since you want to loop back, you need a do-while loop. Read about it? No? Read it and apply it. Let us know if you come across any issues.

Also braces at line no 7 and 12 in your code are redundant. And so are the braces at 17 & 20.
Last edited on
Topic archived. No new replies allowed.