如何比较两个整数,看它们是否相等

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

本文关键字:是否 两个 何比较 比较 整数      更新时间:2023-10-16

如何比较C++中的两个整数?


我有一个用户输入ID(即int),然后有一个联系人ID,它是我的结构的一部分。联系人ID也是int

我需要进行比较,看看它们是否相同,才能知道它的存在。

我做了这样的事*:

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

但我收到一条错误消息,说表达式必须具有类类型。

*基于阅读本页http://www.cplusplus.com/reference/string/string/compare/

您找到的函数用于比较两个std::string s。您没有std::string s,您有int s。要测试两个int s是否相等,只需使用==,如下所示:

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

事实上,即使您有两个std::string,您也很可能希望在那里使用==

我不确定你的意思,但IMHO

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

重点是您不将输入存储为字符串,而是将其存储为int。

    //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;
    }

如果结构的名称是p,并且其中有一个名为hello的整数,则可以执行以下

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;
}
相关文章: