我尝试读取输入的每一行中的第一个字符,然后根据第一个字符确定该行其余部分的格式。然后我使用 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);
并且它们都没有改变输出中的任何内容。我在这里做错了什么?
最佳答案
"\n"
in if (scanf("%s %d %d\n"
阻止 scanf()
返回直到在第二个 int
之后输入非空白。
"\n"
不是简单地扫描 '\n'
,它会扫描所有空白,直到出现另一个非空白。这通常涉及第二行文本,因为用户输入是行缓冲的。
将 '\n'
放在 "%s %d %d\n"
的末尾。
更好的是,使用 fgets()
读取并使用 scanf()
删除。使用 sscanf()
、strtok()
、strtod()
等代替。
关于C - scanf() 之后的 printf() 直到下一个 scanf() 才打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29220388/