0

I followed this tutorial (http://codebase.eu/tutorial/linux-socket-programming-c/) and made a server. The thing is that when the server receives a string from the client, I don't know how to compare it. For example, the following doesn't work:

bytes_received = recv(new_sd, incomming_data_buffer, 1000, 0);

if(bytes_received == 0)
    cout << "host shut down." << endl;

if(bytes_received == -1)
    cout << "receive error!" << endl;

incomming_data_buffer[bytes_received] = '\0';
cout << "Received data: " << incomming_data_buffer << endl;

//The comparison in the if below doesn't work. The if isn't entered
//if the client sent "Hi", which should work
if(incomming_data_buffer == "Hi\n")
{
    cout << "It said Hi!" << endl;
}
1
  • You can't compare pointers (arrays decays to pointers, and string literals are pointers to an array containing the string), as then you compare the pointers and not what they point to. Either use std::string or use std::strcmp. Mar 28, 2015 at 16:11

1 Answer 1

1

You are attempting to compare a character pointer with a string literal (which will resolve to a character pointer), so yeah, the code you have definitely won't work (nor should it). Since your in C++, I would suggest this:

if(std::string(incomming_data_buffer) == "Hi\n")
    cout<<"It said Hi!"<<endl;

Now, you need to include string for this work, but I assume you are already doing this, especially if you are comparing strings using this method other places in your code.

Just an explanation of what's going on here, since you appear to be relatively new to C++. In C, string literals are stored as const char*, and mutable strings are simply character arrays. If you've ever programmed C, you might remember that (char* == char*) doesn't actually compare strings, you would need the strcmp() function for that.

C++, however, introduces the std::string type, which can be directly compared using the '==' operator (and concatenated using the '+' operator). But, C code still runs in C++, so char* arrays are not necessarily promoted to std::string unless they are being operated on by a std::string operator (and even then, if I recall, they aren't so much promoted as the operator allows string/char* comparisons), so (std::string == char*) will perform the expected comparison operation. When we do std::string(char*), we call the std::string constructor, which returns a string (in this case, a temporary one) that is compared with your string literal.

Note that I am assuming incomming_data_buffer is of type char*, you are using it like it is, although I can't see the actual declaration.

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.