无法理解什么是fflush()函数

时间:2018-12-23 18:50:01

标签: c

我似乎无法理解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,但在课堂上没有解释。

1 个答案:

答案 0 :(得分:4)

刷新输出流(例如stdout)会使所有缓冲的数据“刷新”到输出中。例如,由于stdout可能是行缓冲的,所以经常使用刷新stdout来确保输出即使不带换行符也变得可见。

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