C - scanf() 之后的 printf() 直到下一个 scanf() 才打印

标签 c

我尝试读取输入的每一行中的第一个字符,然后根据第一个字符确定该行其余部分的格式。然后我使用 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/

相关文章:

c - AVR C 编程 - 全局数组

c - 如何替换结构中字符串中的字符?

c - 字符串作为c函数中的参数

c - 制作一个字符串数组的数组

C 指针,段错误

c++ - Linux 相当于 WaitCommEvent

c - 在 C 中将#define 与开关状态一起使用

c - 为什么编译器将变量理解为指针,而事实并非如此?

c# - 在 C 系列中,在一个循环中,为什​​么 "less than or equal to"比 "less than"符号更受欢迎?

python - 对 recvbuf 进行操作的 MPI_Sendrecv?