4

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/

cigien
  • 57,834
  • 11
  • 73
  • 112
Amy
  • 71
  • 1
  • 1
  • 8
  • 8
  • 1
    @OliCharlesworth oh my I feel silly haha. Thanks a lot :] – Amy Feb 17 '13 at 18:21
  • Is your `user_input_id` *declared* as an `int`, or is it a `string` that *represents* and `int`? In the first case, `.compare()` makes no sense, cause `int` is a fundamental type. If it is a `string`, then what is the type of `p->id`? Is it a `string` as well, or an `int`? In the second case, you may want to convert the former into an `int`, or the latter into a `string` before performing the comparison – Andy Prowl Feb 17 '13 at 18:21
  • 3
    Have a break from coding for a while. Find some good book and study for some time. Have a look at [The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – LihO Feb 17 '13 at 18:23
  • Since we have no idea how the struct is defined (because you didn't post it), do you need to convert from `string` to `int` then compare? – Thomas Matthews Feb 17 '13 at 18:47

4 Answers4

7

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.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
0

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.

xis
  • 24,330
  • 9
  • 43
  • 59
0
    //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;
    }
Cereal_Killer
  • 304
  • 2
  • 13
0

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;
}
muneebahmad
  • 119
  • 1
  • 3