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



当尝试将char缓冲区与if语句中的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("%sn", buffer);

string cmd = bufferToString(buffer, sizeof(buffer));
printf("%s", cmd.c_str());
if (cmd.c_str() == "help") //HERE is the issue
{
printf("hello");
}
}
}

当比较不起作用时我尝试过使用不同类型的字符缓冲区[1024]到字符串的转换,但没有得到任何

编辑:到目前为止我已经试过

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

if (0 == ::std::strcmp(buffer, "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.

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

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

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

您应该执行

cmd.resize(dwRead);

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

或者你必须打电话给

string cmd = bufferToString(buffer, dwRead);

这应该具有相同的效果(没有看到bufferToString的实施(。

此外,你的比较是错误的。在c++中,您可以执行

if (cmd == "help")

这应该有效:

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

代码:

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

将比较指针(从cmd.c_str((返回的#1;"帮助"(,这不是很正确的

最新更新