Problem with my code (Extremely new to programing)

I've been trying to get this code to work, but when i build and run it, it doesnt matter what name is inputted. As if the "if" statement didnt exist.
Would greatly appreciate some help with this! :)

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
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string name = "";

    cout << "What is your name?\n";
    cin >> name;

    if(name == "Alice" || "Bob")
    {
        cout << "Hello" << name << ".\n";

    }
     else
     {
         cout << "Bye" << name << ".\n";
     }




}
Last edited on
As if the "if" statement didnt exist.

That's because your if statement is faulty. C++ does not support an implied left hand side.
Your if statement evaluates as follows (note the parens for clarity):
 
if ( (name == "Alice") || ("Bob") )

("Bob") will always evaluate to true.

You need to code your if state as:
 
if ( name == "Alice" || name == "Bob" )

Ohh, i understand! Thank you so much for helping! ^.^ i Will redo the code once i get home from school.
or he could use like

 
if ( name == "Alice" && "Bob" == name )

xD
@ vaiandrept4, that will not work.
'name' can not be 'Alice' AND 'Bob' at the same time.
Actually i tested it and it work, but the && in this case means "or" too.
Very strange.
Last edited on
I bet what's happening is that it evaluated like this: if((name) == ("Alice" && "Bob") == (name))

This can be corrected by using parenthesis to emphisize the order of operations that you want to have happen.

It makes code more readable, but also removes room for error.
Last edited on
wtf? Just write it like AbstractionAnon stated in the first reply. It's clear and concise.
Last edited on
@vaiandrept4
Can you show the code you used to test, because I don't believe it worked. See http://ideone.com/AqKmFt

And can you explain how and also means or in that case?
Topic archived. No new replies allowed.