C ++如何比较2个整数以查看它们是否相等?一个是用户输入,另一个是结构的一部分?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14924383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:49:55  来源:igfitidea点击:

C++ How to compare 2 integers to see if they are equal? One is user input and the other is part of a struct?

c++integercompare

提问by Amy

I have an 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.

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

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

我需要比较看看它们是否相同,如果它们相同,那么我知道它存在。

This is the closest thing I found but it is not working: http://www.cplusplus.com/reference/string/string/compare/

这是我发现的最接近的东西,但它不起作用:http: //www.cplusplus.com/reference/string/string/compare/

From reading that page, I did something like:

通过阅读该页面,我做了类似的事情:

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

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

我收到错误消息,指出表达式必须具有类类型。

How do I compare two integers in C++?

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

回答by Joseph Mansfield

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:

您找到的函数用于比较两个std::strings。你没有std::strings,你有ints。要测试两个ints 是否相等,您只需==像这样使用:

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

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

事实上,即使你有两个std::strings,你也很可能想在==那里使用。

回答by xis

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.

关键是您不将输入存储为字符串,而是一个 int。

回答by Cereal_Killer

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

回答by muneebahmad

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

如果您的结构名称是 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;
}