【问题标题】:Can't Understand what a fflush() function [duplicate]无法理解 fflush() 函数是什么 [重复]
【发布时间】:2019-05-23 04:40:05
【问题描述】:

我似乎无法理解 C 中 fflush() 函数的概念。谁能用更简单的术语解释一下,因为我似乎无法理解它以及它在这段代码中的作用:

int main() {
    loadContactList();
    while (1) {
        printf("\n");
        printMenu();

        int choice;

        scanf(" %d", &choice);
        fflush(stdin);
        printf("\n");

        if (choice == 1) {
           // addContact();
        } else if (choice == 2) {

        } else if (choice == 3) {

        } else if (choice == 4) {
            query();
        } else if (choice == 5) {
            while (1) {
                printf("choose the sorting mode:\n \n");
                printf("1. Sort by last name, first name then number\n");
                printf("2. Sort by date\n");
                printf("Enter -1 to return to the main menu\n");

                int x;

                scanf("%d", &x);

                if (x == 1) {
                    sortByLFN();
                    printContactList();
                    break;
                } else if (x == 2) {
                    sortByDate();
                    printContactList();
                    break;
                } else if (x == -1) {
                    break;
                }
            }
        } else if (choice == 6) {
            //saveContact();
        } else if (choice == 7) {
            quitPhoneBook();
        } else {
            printf("You entered an invalid option \n");
        }    
    }
    return 0;
}

代码应该用于电话簿程序,我们被告知使用fflush,但在课堂上没有解释。

【问题讨论】:

  • 这里的大多数人可能会建议不要刷新输入,而是使用缩进和更少的空格。
  • 建议的副本是间接的。刷新输入是未定义的行为(请参阅建议的欺骗中赞成但未接受的答案)。这间接地给出了“在这段代码中使用flush做什么?一点也不”的答案。也可以在该问题中找到要做什么。如果老师告诉您在输入时使用flush,这会很棘手......
  • 请注意,刷新输出是有意义的。我习惯于通过适当使用换行符(在大多数环境中允许足够的输出控制)来实现所需的输出,但刷新是另一种方法,在某些情况下是必要的(我相信)。
  • 与您的问题无关,但我建议您了解switch 声明。
  • 你读过documentation of fflush吗?

标签: c


【解决方案1】:

刷新输出 流(例如stdout)会导致任何缓冲数据“刷新”到输出。例如,经常使用刷新stdout 来确保输出可见,即使它后面没有换行符,因为stdout 可能是行缓冲的。

刷新 input 流(例如 stdin)在标准 C 中是未定义的行为,不应使用。一些实现确实将其定义为 非标准 扩展以清除任何未读输入,但我强烈建议不要利用它(特别是作为不当使用 scanf 的解决方法)。问题中的代码属于这一类。

【讨论】:

    猜你喜欢
    • 2013-03-11
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 2013-07-15
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多