IF always gives me the same answer!

Asked

Viewed 68 times

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 as follows, in case I enter with "drink" the if I come back with "This right" otherwise "This wrong".

What happens is that no matter what I write, he always returns to me with "This Right".

  • 1

    which return? what you expect?

  • 1

    you do not initialize the variable "drink", so it was always going to be 0, that’s what you want?

  • The return I want to get is the following, In case I enter with "drink" the if me comes back with "This right" otherwise "This wrong". What happens is that regardless of what I write, it always returns to me with "This right".

  • @Math in c++ is not memory junk the value of the uninitialized variable?

  • 1

    @Jeffersonquesado do not remember the theory well, but I did a test and that was the result: https://ideone.com/pRqk34

2 answers

5


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

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

In short, it’s 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 on Ideone

When you say :

What happens is that no matter what I write, he always returns to me with "This Right".

It’s because in your original code you stated x and bebida as integers, the variable bebida you never started, so she assumed the value of 0, already for the variable x you wrote a string, so it was also worth 0 and the comparison of the two variables returned true.

1

How 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;
}
  • Wow is exactly what I wanted to do! Friend(a) could you explain me the solution?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.