【发布时间】:2021-01-04 03:15:44
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void eat() // clears stdin upto and including \n OR EOF
{
int eat;while ((eat = getchar()) != '\n' && eat != EOF);
}
int main(){
printf("\n COMMAND : "); char cmd[21]=""; scanf("%20s",cmd);
if(strcmp(cmd,"shell")==0||strcmp(cmd,"sh")==0)
{
getchar(); // absorb whitespace char separating 'shell' and the command, say 'ls'
while(1)
{
printf("\n sh >>> "); // print prompt
char shellcmd[1024]=""; // str to store command
scanf("%1023[^\n]",shellcmd); eat(); // take input of command and clear stdin
if(strcmp("close",shellcmd)==0||strcmp("x",shellcmd)==0)
break;
else
system(shellcmd);
}
}
}
在代码中,发生了一些我无法捕捉到的异常行为。
输入sh ls 并按[ENTER] 后,预期的响应是:
- 第一个
scanf()将sh存储在cmd[]中,并将ls\n留在stdin中。 -
getchar()占用空间。 -
printf()打印\n sh >>>到终端 - 第二个
scanf()在shellcmd[]中存储ls,在标准输入中留下\n -
eat()从标准输入读取\n,将其留空 -
system("ls")被执行
即结果应该是这样的:
COMMAND : sh ls
sh >>>
file1 file 2 file3 ...
sh >>> | (cursor)
但是
我得到了什么:
COMMAND : sh ls
file1 file2 file3 ...
sh >>>
sh >>> |
显然,第二个 scanf() 和 shell() 正在执行之前 printf(),或者至少这是我的假设。
怎么了?
使用 cc -Wall -Wextra -pedantic 在 Clang 和 GCC 上编译,并在 MacOS 和 Linux 上的 bash 上进行测试
【问题讨论】:
标签: c shell io stdin console-input