strcmp on char *编译,但不起作用

时间:2013-11-14 21:32:00

标签: c linux char strtok strcmp

我试图通过空格分解char,然后执行一些条件逻辑,但在char *上使用strcmp不起作用。

int main(void)
{
    char buf[64];
    char *cmd;

    // assign some space delimited words to buf...

    if (strcmp(buf, "somestring junk") == 0) { // this works
        // do stuff here
    }

    cmd = strtok(buf, " ");

    if (strcmp(cmd, "somestring") == 0) { // this doesn't work
        // do stuff here
    }

    return 0;
}

我尝试过不同的变体,例如“somestring”或“somestring \ n”,但没有成功。代码编译时没有错误或警告。 strcmp的手册让我相信strcmp应该可行。我做错了什么?

1 个答案:

答案 0 :(得分:1)

它没有工作,因为你有cmd和buf在strcmp中混淆了。以下代码适合您:

#include <stdio.h>
#include <cstring>

int main(void)
{
    char buf[64] = "somestring junk";
    char *cmd;

    // assign some space delimited words to buf...

    if (strcmp(buf, "somestring junk") == 0)
    {
            printf("First strcmp works!\n");
    }

    cmd = strtok(buf, " ");

    if (strcmp(cmd, "somestring") == 0)
    {
        printf("Second strcmp works!");
    }

    return 0;
}