繁体   English   中英

C-scanf()之后的printf()在下一个scanf()之前不打印

[英]C - printf() after scanf() not printing until next scanf()

我试图读取输入的每一行中的第一个字符,然后基于第一个字符,确定其余行所采用的格式。然后,我使用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

基本上,在调用下一个processCommand()之前,不会将printf刷新到标准输出。 我已经尝试了所有这些方法:

fflush(stdin);
while ( getchar() != '\n' );
fflush(stdout);
setbuf(stdout, NULL);
setvbuf(stdout, NULL, _IONBF, 0);

而且它们都没有改变输出。 我在这里做错了什么?

if (scanf(" %s %d %d\\n"阻止scanf()返回,直到在第二个int之后输入非空白为止, if (scanf(" %s %d %d\\n" "\\n"

"\\n"不会简单地扫描'\\n' ,它会扫描所有空白,直到出现另一个非空白。 由于用户输入是行缓冲的,因此通常涉及第二行文本。

'\\n'放在" %s %d %d\\n"的末尾。

更好的是,使用fgets()阅读并使用scanf()删除。 请改用sscanf()strtok()strtod()等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM