简体   繁体   中英

How to compare const char* with a string in C++?

I am working with C++ and I am trying to compare strings.

Below is my code which gives me back const char* -

    const char* client_id() const {
        return String(m_clientPos);
    }

And now I am comparing the strings like this -

cout<<client_ptr->client_id()<< endl;
if (strcmp(client_ptr->client_id(), "Hello")) {
    ..
} else {
    ..
}

but it never goes into if statement. But my cout prints out Hello correctly. Is there anything wrong I am doing?

You need to do if (0 == strcmp(...

See http://www.cplusplus.com/reference/cstring/strcmp/

strcmp

Returns an integral value indicating the relationship between the strings: A zero value indicates that both strings are equal. A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite.

it never goes into if statement.

The strcmp function returns zero when the strings are the same, so you should see the code hit the else branch when the two strings are equal to each other.

  • A zero value indicates that both strings are equal.
  • A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2;
  • And a value less than zero indicates the opposite.

Since String does not look like a built-in class and assuming that you have access to its source, you may be better off making the comparison with const char* a member function of the String class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM