【问题标题】:Comparing received string on server side - C++比较服务器端接收到的字符串 - C++
【发布时间】:2015-03-28 16:06:54
【问题描述】:

我按照本教程 (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] = '\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;
}

【问题讨论】:

  • 你不能比较指针(数组衰减为指针,字符串文字是指向包含字符串的数组的指针),因为然后你比较 pointers 而不是它们指向。要么使用std::string,要么使用std::strcmp

标签: c++ networking client server


【解决方案1】:

您正在尝试将字符指针与字符串文字(将解析为字符指针)进行比较,所以是的,您拥有的代码肯定行不通(也不应该)。由于您使用 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 构造函数,它返回一个字符串(在本例中是一个临时字符串),该字符串与您的字符串字面量进行比较。

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

【讨论】:

    猜你喜欢
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多