0

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?

7
  • 2
    where it prints "hello"? Commented May 21, 2014 at 2:43
  • 1
    why you converting m_clientIdPos to string if the return type is const char*? Commented May 21, 2014 at 2:43
  • 2
    I meant where is the print statement? Commented May 21, 2014 at 2:44
  • That's not my code base. Somebody else wrote it like that. Is there any problem with that? Commented May 21, 2014 at 2:44
  • 1
    there is obvious problem, String is not built in type, (did u mean string?). if there is a user defined String type, then the code will not compile Commented May 21, 2014 at 2:45

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.