将 char 缓冲区与字符串进行比较不起作用

comparing char buffer to string not working

当尝试在 if 语句中将 char 缓冲区与 std 字符串进行比较时,它没有按预期工作 这是代码

if (ConnectNamedPipe(hPipe, NULL) != FALSE)   // wait for someone to connect to the pipe
    {
        while (ReadFile(hPipe, buffer, sizeof(buffer) - 1, &dwRead, NULL) != FALSE)
        {
            /* add terminating zero */
            buffer[dwRead] = 0x00;

            /* do something with data in buffer */
            printf("%s\n", buffer);
            
            string cmd = bufferToString(buffer, sizeof(buffer));

            printf("%s", cmd.c_str());

            if (cmd.c_str() == "help") //HERE is the issue
            {
                printf("hello");
            }

        }
    }

比较时不起作用 我试过使用不同类型的 char buffer[1024] 到字符串的转换,但没有得到任何结果

编辑: 我已经试过了

    cmd.resize(dwRead);
if (cmd == string("help")) 

if (0 == ::std::strcmp(buffer, "help"))

none 他们工作

您正在创建复制 sizeof(buffer) 个字符的字符串,而它只包含 dwRead 个初始化字符。

然后你比较两个指针而不是字符串内容(这仍然行不通,因为 cmd 的长度错误)。您实际上应该比较使用 strcmp 而不创建临时 std::string 对象。

if (0 == ::std::strcmp(buffer, "help"))
{
    printf("hello");
}

这应该有效:

if (cmd == string("help")) // should work
{
    printf("hello");
}

代码:

if (cmd.c_str() == "help") 

将比较指针(#1 从 cmd.c_str() 返回,#2 - 指向“帮助”的常量指针),这不太正确

你应该做

cmd.resize(dwRead);

这会将字符串设置为实际读取数据的长度,而不是整个缓冲区。 C++ std::string 可以包含任何数据,包括 0-bytes.

或者您必须致电

string cmd = bufferToString(buffer, dwRead);

应该是一样的效果(没看到bufferToString的实现)

你的比较也是错误的。在 C++ 中你会做

if (cmd == "help")

您可以直接使用 std::string,而不是将数据读入 char[],然后将该数据复制到 std::string

积木:

std::string cmd;

cmd.resize(wanted_buffer_size); // Set the proper buffer size

ReadFile(hPipe, cmd.data(), cmd.size(), &dwRead, nullptr); // Read directly into cmd

cmd.resize(dwRead); // Shrink down to dwRead afterwards. Automatically null terminated.