0 c
我似乎无法理解fflush()C语言中函数的概念。有人可以用更简单的术语来解释它,因为我似乎无法理解它及其在代码中的作用:
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;
}
Run Code Online (Sandbox Code Playgroud)
该代码应该是用于电话簿程序的,我们被告知要使用,fflush但课堂上没有解释。
冲洗的输出流(如stdout)导致所有缓冲的数据被“刷新”,以输出。例如,stdout由于stdout可能是行缓冲的,所以经常使用刷新来确保即使输出后没有换行符,输出也变得可见。
刷新输入流(例如stdin)是标准C中的未定义行为,因此不应使用。某些实现确实将其定义为清除所有未读输入的非标准扩展,但我强烈建议您不要利用此扩展(尤其是作为不当使用的解决方法scanf)。问题中的代码属于此类。