【发布时间】:2014-03-10 19:14:23
【问题描述】:
我正在编写一个充当简单外壳的程序。用户从命令行调用程序并提示输入发送到操作系统以完成的命令。它应该一直运行到用户输入“完成”,此时程序应该中断。我在输入 done 时遇到问题 - 程序按原样退出,但打印出来
sh: -c: line 0: syntax error near unexpected token `done'
sh: -c: line 0: `done'
在完成执行之前到终端。这是我编写的适用的代码:
char isDone[] = "done\n"; //fgets stores the new line character from the command line
do {
printf(">>"); //print the prompt each time through the loop
fgets(command, 50, stdin); //get a line from the terminal
system(command);
} while (strcmp(command, isDone) != 0); //break the loop if the user types in done
我认为该错误与“完成”不是有效的 UNIX 命令这一事实有关,但我不确定如何处理此错误。我尝试通过以下修复解决此问题:
if(system(command) == -1){
printf("The OS doesn't recognize this command");
}
else
system(command);
但这并没有解决问题或将错误打印到屏幕上,并产生了第二个问题,即两次打印命令/错误 - 一次在 if 条件块中,一次在 else 块中。我该如何解决这个问题?
编辑 这是一个家庭作业问题,需要使用 do-while。有没有使用 do-while 的解决方案?
【问题讨论】:
标签: c error-handling system