首页 > 解决方案 > 为什么输入某些内容并按回车后scanf不会停止

问题描述

代码只是继续接受输入,并没有继续 if 逻辑,我不知道为什么

    while (1){

    // get command
    char cmd[6];
    scanf("%s", cmd);

    if (cmd == "exit"){
        return 0;
    } else if(cmd == "task\n"){
        taskHandler();
    } else if(cmd == "event"){
        eventHandler();
    } else if(cmd == "show"){
        showItems();
    }
}

标签: c

解决方案


在 C 中,您不能使用==比较字符串,因为它会比较指针的值,即内存中具有字符串数据的位置。如果要比较实际数据,则必须使用strcmp,即:

if(cmd == "exit") {
  ...
}

应该

if(strcmp(cmd, "exit") == 0) {
  ...
}

int strcmp(const char* str0, const char* str1)返回是否str1按字典顺序小于、等于或大于(-1分别为0、 和1),所以如果它返回0,则str0str1相等。

我也会使用break代替 thereturn 0并将 the移到循环return 0之外。while(1)


推荐阅读