"If else" statements problem

So everytime I try to get the "if else" statement to work, it never does for me. I will give you my example in this case. I am trying to input the word "hello" and get a response of "Hi". However, I always seem to get this problem whereby it runs both the cout of the "if" statement and also the cout of the "else" statement, despite them both being a different paremeter to check. Can someone give me the answer? Thanks for your time.

Cee

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

int main()
{
    string setname;
    int hello;
    cout << "Enter Hello:" << endl;
    cin >> setname;

    if (setname == "hello")
        {
        cout << "Hi \n";
        }
        else (setname != "hello");
        {
            cout << "youve got the wrong word!";
        }
}
Last edited on
Either you should write

1
2
3
4
       else if (setname != "hello")
        {
            cout << "youve got the wrong word!";
        }


or simply

1
2
3
4
       else // (setname != "hello")
        {
            cout << "youve got the wrong word!";
        }
Last edited on
Thanks buddy
Due to the semicolon in the end of this statement

else (setname != "hello");

the code of if-else statement looks in fact the following way


1
2
3
4
5
6
7
8
9
10
11
12
13
    if (setname == "hello")
        {
        cout << "Hi \n";
        }
        else 
        {
                (setname != "hello");
        }

        // some code block
        {
            cout << "youve got the wrong word!";
        }

So this statement

cout << "youve got the wrong word!";

will be executed in any case.:) This is the cost of wrong placing of a semicolon.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    string setname;
    int hello;
    cout << "Enter Hello:" << endl;
    cin >> setname;

    if (setname == "Hello")//<<<it says "Enter Hello" not hello
      //  {
        cout << "Hi \n";
        //}
        else //(setname != "hello");
        //{
            cout << "youve got the wrong word!";
        //}
}


what is int hello;for?
Topic archived. No new replies allowed.