我正在尝试读取输入的每行第一个字符,然后根据第一个字符确定其余部分的格式。接着,根据所接收到的命令使用scanf()函数读取值。
char name[50];
int rating, ref;
int main() {
int command;
while (command = getchar()) {
if (command == EOF || command == '\0') break;
if (!processCommand(command)) break;
printf("done processing, waiting for new command\n");
}
}
char processCommand(int command) {
switch (command) {
case 'a':
printf("starting\n");
if (scanf(" %s %d %d\n", name, &rating, &ref) != 3) return 0;
// SOME PROCESSING
printf("done\n");
break;
default:
exit(EXIT_FAILURE);
}
return 1;
}
问题在于输出结果看起来像这样:
./program.out
a Test 5 12345
starting
a Testing 0 23456
done
done processing, waiting for new command
starting
基本上,printf
不会被刷新到标准输出流直到下一个processCommand()
被调用。我已经尝试了以下所有方法:
fflush(stdin);
while ( getchar() != '\n' );
fflush(stdout);
setbuf(stdout, NULL);
setvbuf(stdout, NULL, _IONBF, 0);
它们都不会改变输出结果。我在这里做错了什么吗?
int
,因为getchar()
返回的是一个int
。 - pzaengerscanf(" %s %d %d\n"...
这段代码有点可疑。最后的"\n"
可能会读入比预期更多的内容。 - chux - Reinstate Monicagetchar()
和scanf()
不太兼容。最好只使用scanf()
,因为无论如何,您的键盘输入都是行缓冲的。此外,请阅读scanf()
的手册页面。您不需要在其中使用\n
。 - r3mainer\n
才是问题的原因。 - Xeos