IF always gives me the same answer!

2
#include <iostream>

using namespace std;

int main(){

    int x, bebida;

    cout<<"Digite 'bebida' "<<endl;
    cin>>x;

    if(x == bebida){
        cout<<"Esta certo"<<endl;
    }
    else{
        (x != bebida);
        cout<<"Esta errado"<<endl;
    }
    return 0;
}

The return I want to get is the following, if I enter "drink" the if returns me with "This right" otherwise "This is wrong".

What happens is that regardless of what I write, it always returns me with "It's Right".

    
asked by anonymous 26.09.2017 / 20:53

2 answers

5

You created a variable with the name "drink" when you should actually use a literal string, if you want to compare a variable with a string this variable must also be of type string , so change the declaration of your x to string and delete the variable bebida .

Also within your else has an attempt to compare style else if which is unnecessary, so it can simply be removed.

Summarizing everything, it looks like this:

#include <iostream>

using namespace std;

int main(){

    string x;

    cout<<"Digite 'bebida' "<<endl;
    cin>>x;

    if(x == "bebida"){
        cout<<"Esta certo"<<endl;
    }
    else{
        cout<<"Esta errado"<<endl;
    }
    return 0;
}

See working at Ideone

When you say:

  

What happens is that regardless of what I write, it always returns me with "It's Right".

It's because in your original code you declared x and bebida as integers, the variable bebida you never initialized, so it assumed the value of 0 , already for the variable x you wrote a string, then it also got value of 0 and the comparison of the two variables returned true.

    
26.09.2017 / 21:18
1

What about:

#include <iostream>
#include <string>

using namespace std;

int main(){

    string x;

    cout << "Digite 'bebida' " << endl;

    cin >> x;

    if( x == "bebida" ) {
        cout<<"Esta certo"<<endl;
    }else{
        cout << "Esta errado" << endl;
    }

    return 0;
}
    
26.09.2017 / 21:06