简体   繁体   English

循环无法停止

[英]Loop can't stop

I'm trying to build a program which runs in command line written in C looks like that: 我正在尝试构建一个以C编写的在命令行中运行的程序,如下所示:

int main(void){

    char code[25];
    char *fullCmd;
    char *command;
    char *extraCmd;

    bool stop = false;
    int loop = 1;

    while (loop == 1){

        printf("C:\\>");
        scanf("%[^\n]",code);

        fullCmd = strdup(code);
        command = strtok(fullCmd, " ");
        extraCmd = strtok(NULL, " ");
        handStatement(code, command, extraCmd); 

        if(strcmp(command,"exit\n") == 0 || strcmp(command, "quit\n") == 0){
            loop = 0;
            printf("Program Terminated\n");
        }
    }

    return 0;
}

HandStatement() is one of my handles. HandStatement()是我的句柄之一。 But problems in here is that the while loop won't stop for me to enter another command when handStatement() is executed. 但是这里的问题是,当执行handStatement()时,while循环不会停止让我输入另一个命令。 If I don't use while, I can execute one command at a time. 如果我不使用一段时间,则可以一次执行一个命令。

You don't need trailing \\n characters in your strcmp call. 您在strcmp调用中不需要结尾\\n字符。

    if(strcmp(command,"exit") == 0 || strcmp(command, "quit") == 0){
        loop = 0;
        printf("Program Terminated\n");
    }

Also, you need to flush newline characters from stdin: 另外,您需要从stdin刷新换行符:

while (loop == 1){
    printf("C:\\>");
    scanf("%[^\n]",code);
    fullCmd = strdup(code);
    command = strtok(fullCmd, " ");
    extraCmd = strtok(NULL, " ");
    handStatement(code, command, extraCmd);
    if(strcmp(command,"exit") == 0 || strcmp(command, "quit") == 0){
        loop = 0;
        printf("Program Terminated\n");
    }
   /* Flush whitespace from stdin buffer */
   while(getchar() != '\n');
}

If you remove the '\\n' from your code, it will work. 如果从代码中删除“ \\ n”,它将起作用。 Unless your termination character has been changed, it will not actually place the newline character into the string and therefore your strcmp() will always return not equal. 除非更改了终止符,否则它实际上不会将换行符放入字符串中,因此您的strcmp()将始终返回不相等的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM