networking - Comparing received string on server side - C++ -


i followed tutorial (http://codebase.eu/tutorial/linux-socket-programming-c/) , made server. thing when server receives string client, don't know how compare it. example, 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 if below doesn't work. if isn't entered //if client sent "hi", should work if(incomming_data_buffer == "hi\n") {     cout << "it said hi!" << endl; } 

you attempting compare character pointer string literal (which resolve character pointer), yeah, code have won't work (nor should it). since in c++, suggest this:

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

now, need include string work, assume doing this, if comparing strings using method other places in code.

just explanation of what's going on here, since appear relatively new c++. in c, string literals stored const char*, , mutable strings character arrays. if you've ever programmed c, might remember (char* == char*) doesn't compare strings, need strcmp() function that.

c++, however, introduces std::string type, can directly compared using '==' operator (and concatenated using '+' operator). but, c code still runs in c++, char* arrays not promoted std::string unless being operated on std::string operator (and then, if recall, aren't promoted operator allows string/char* comparisons), (std::string == char*) perform expected comparison operation. when std::string(char*), call std::string constructor, returns string (in case, temporary one) compared string literal.

note assuming incomming_data_buffer of type char*, using is, although can't see actual declaration.


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -