C++ strcmp 数组

发布于 2024-08-06 13:19:06 字数 492 浏览 6 评论 0原文

我正在使用 strcmp ,如下所示。

我正在调试值 和 ,它们是相同的,但仍然没有使该条件成立。

const char opcode_read[2] = {'0', '1'};

rc = recvfrom(s, blk_receive_full, sizeof (blk_receive_full), 0,(struct sockaddr FAR *)&sin, &fromlength);

if(rc == -1){
    printf("failed: recvfrom, \n No data received \n failed code: %d\n",WSAGetLastError());
    cleanup();
    exit(1);
}

memcpy(blk_receive_opcode, &blk_receive_full, 2);
if (strcmp(blk_receive_opcode, opcode_data) == 0) {
}

I am using strcmp as shown below.

I am debugging the values and which are coming same but still not getting that condition true.

const char opcode_read[2] = {'0', '1'};

rc = recvfrom(s, blk_receive_full, sizeof (blk_receive_full), 0,(struct sockaddr FAR *)&sin, &fromlength);

if(rc == -1){
    printf("failed: recvfrom, \n No data received \n failed code: %d\n",WSAGetLastError());
    cleanup();
    exit(1);
}

memcpy(blk_receive_opcode, &blk_receive_full, 2);
if (strcmp(blk_receive_opcode, opcode_data) == 0) {
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

当爱已成负担 2024-08-13 13:19:06

据我所知,您没有比较两个字符串,因为它们不是以空终止的。您可能想使用 memcmp() 代替:

if (memcmp(blk_receive_opcode, opcode_data, 2) == 0) {
}

From what I can tell, you aren't comparing two strings as they aren't null-terminated. You may want to use memcmp() instead:

if (memcmp(blk_receive_opcode, opcode_data, 2) == 0) {
}
天冷不及心凉 2024-08-13 13:19:06

您可能想尝试 memcmpstrcmp 用于空终止字符串。

You might want to try memcmp instead. strcmp is for null terminated strings.

我不在是我 2024-08-13 13:19:06

opcode_read 不是字符串。没有 NUL 终止。
将其大小更改为 3,这样您就可以在第三个位置找到一个 NUL。

const char opcode_read[3] = {'0', '1'};

另一种方法是使用 memcmp 而不是 strcmp,这样您就不必担心讨厌的 NUL 终止符。

recvfrom 调用也有点可怕。如果我没记错的话我的 TCPIP 的话。不保证该函数在一次调用中会返回 2 个字节。它可能在第一次调用中返回一个字节,在第二次调用中返回第二个字节。

opcode_read is not a string. There is no NUL termination.
Change its size to 3, so you pick up a NUL in the third position.

const char opcode_read[3] = {'0', '1'};

An alternative would be to use memcmp instead of strcmp so you don't have to worry about the pesky NUL terminator.

The recvfrom call is a bit scary too. If I recall my TCPIP correctly. There is no guarantee that the function will return 2 bytes in one call. It may return one byte, in the first call, and the second byte in the second call.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文