我正在尝试构建一个在用 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/