c - 循环无法停止

标签 c windows command

我正在尝试构建一个在用 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() 是我的 handle 之一。但是这里的问题是,当执行 handStatement() 时,while 循环不会停止让我输入另一个命令。如果我不使用 while,我可以一次执行一个命令。

最佳答案

您的 strcmp 调用中不需要尾随 \n 字符。

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

此外,您需要从标准输入中清除换行符:

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');
}

关于c - 循环无法停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18041427/

相关文章:

c - 信号处理函数+不忽略SIGINT

c# - Windows 8.1 联系人列表

windows - Perforce:如何从更改列表创建文件列表?

c++ - 如何绘制粗线的轮廓?

c# - 导入用 C 或 C# 编写的 dll 文件

c - 在双向链表中搜索值并输入之前

c++ - 一个过去的对象结束指针

Linux - 替换文件名中的空格

shell - 批处理文件在 mvn 命令后停止执行

c# - 如何使用私有(private)方法调整 C# 类?