比较服务器端接收到的字符串 - C++

Comparing received string on server side - C++

我按照本教程 (http://codebase.eu/tutorial/linux-socket-programming-c/) 制作了一个服务器。问题是,当服务器从客户端收到一个字符串时,我不知道如何比较它。例如,以下内容不起作用:

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] = '[=10=]';
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;
}

您正在尝试将字符指针与字符串文字(将解析为字符指针)进行比较,所以是的,您拥有的代码肯定行不通(也不应该)。因为你在 C++ 中,我会建议这个:

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

现在,您需要为此工作包含字符串,但我假设您已经这样做了,尤其是当您在代码的其他地方使用此方法比较字符串时。

只是解释一下这里发生了什么,因为您似乎是 C++ 的新手。在 C 中,字符串文字存储为 const char*,而可变字符串只是字符数组。如果您曾经编写过 C 语言,您可能会记得 (char* == char*) 实际上并不比较字符串,为此您需要 strcmp() 函数。

然而,

C++ 引入了 std::string 类型,可以使用“==”运算符直接比较(并使用“+”运算符连接)。但是,C 代码仍然在 C++ 中运行,因此 char* 数组不一定被提升为 std::string 除非它们由 std::string 运算符操作(即便如此,如果我记得的话,它们不是由于运算符允许 string/char* 比较),因此得到了很大提升,因此 (std::string == char*) 将执行预期的比较操作。当我们执行 std::string(char*) 时,我们调用 std::string 构造函数,其中 returns 一个字符串(在本例中为临时字符串)与您的字符串文字进行比较。

请注意,我假设 incomming_data_buffer 是 char* 类型,您按原样使用它,尽管我看不到实际的声明。