我的strcmp函数有什么问题?

时间:2015-05-04 18:36:06

标签: c

我的代码是:

getline(&cmd, &len, stdin);
cmd[strcspn(cmd,"\n")] = 0;
char *ncmd = (char*)malloc(strlen(cmd) + 1);
memset(ncmd, '\0', strlen(cmd));
strcpy(ncmd,cmd);

const char *tok = strtok(ncmd, " ");


// token is just string from stdin
if(!strcmp(tok, "bye")){
    printf("bye");
} else if (!strcmp(tok, "help")){
    printf("help");
} else if (!strcmp(tok, "list")){
    ......
}

即。输入:help和bye

Result: TOK: help
        strcmp(tok, "bye"): 6
        strcmp(tok, "help"): 0
        strcmp(tok, "list"): -10

Result: TOK: bye
        strcmp(tok, "bye"): 0
        strcmp(tok, "help"): -6
        strcmp(tok, "list"): -4

无论我输入什么,我似乎无法提出正确的if语句。 我如何修复" strcmp"函数,所以它转到正确的if语句?

3 个答案:

答案 0 :(得分:1)

由于代码和if语句是正确的,我认为tok有额外的字符,例如换行符。那么tok将永远不会等同于你的任何一个词。

答案 1 :(得分:0)

创建与form.ShowDialog();一起使用的缓冲区时,通常会多次使用相同的缓冲区。因此,而不是将其声明为:

strtok()

创建它以便可以更改:

const char *tok = strtok(ncmd, " "); //tok cannot be changed (const keyword)

示例:

char *tok = strtok(ncmd, " ");//tok can be changed  (removed const keyword) 

答案 2 :(得分:0)

我没有正确理解您的代码,但我希望这是您在代码中尝试实现的目标:

int main()
{
    char list[] = "bye help list";
    char *delim = " ";
    char *pch = strtok(list,delim);
    int count = 0;
    while(pch) {
        if(!strcmp(pch,"bye")) {
            printf("i found bye at %d\n",count);
        } else if (!strcmp(pch,"help")) {
            printf("i found help at %d\n",count);
        } else if (!strcmp(pch,"list")) {
            printf("i found list at %d",count);
        }
        count++;
        pch = strtok(NULL,delim);
    }
    printf("\n");
    return 0;
}