【发布时间】: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声明。
标签: c