'How to compare 2 integers to see if they are equal?

How do I compare two integers in C++?


I have a user input ID (which is int) and then I have a Contact ID that is part of my Struct. The Contact ID is int also.

I need to compare to see if they are the same, to know that it exists.

I did something like this*:

if(user_input_id.compare(p->id)==0) 
{
}

but I get an error message saying that expression must have class type.

*based on reading this page http://www.cplusplus.com/reference/string/string/compare/



Solution 1:[1]

The function you found is for comparing two std::strings. You don't have std::strings, you have ints. To test if two ints are equal, you just use == like so:

if (user_input_id == p->id) {
  // ...
}

In fact, even if you had two std::strings, you'd most likely want to use == there too.

Solution 2:[2]

I am unsure what you mean, but IMHO

int k;
std::cin>>k;
if (k==p->id) 
    do_sth();
else
    do_sth_else();

The point is you do not store input as string, but a int.

Solution 3:[3]

    //simple program to compare
    #include<iostream>
    using namespace std;
    typedef struct node {
        int a;
    }node;
    int main() {
        node p;
        p.a = 5;
        int a;
        cin >> a;
        if( p.a == a )
            cout << "Equal" << endl;
        else 
            cout << "Not Equal"<< endl;
        return 0;
    }

Solution 4:[4]

IF your struct's name is p and you have an integer in it called hello, you can do the following

int input;
cin << input;
if(input == p.hello){
    cout << "the input is equal to p.hello" << endl;
}
else{
    cout << "the input is not equal to p.hello" << endl;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joseph Mansfield
Solution 2 xis
Solution 3 Cereal_Killer
Solution 4 muneebahmad