program source code我应该如何使用fflush
OS/X 上的 C 语言?当我使用它时,它不会清除缓冲区并立即终止程序。
最佳答案
调用fflush(stdin);
会调用未定义的行为。您不应该使用它来刷新标准输入缓冲区中的字符。相反,您可以读取字符直到下一个换行符并忽略它们:
int c;
while ((c = getchar()) != EOF && c != '\n')
continue;
您也可以使用 scanf()
来实现此目的,但这很棘手:
scanf("%*^[\n]"); // read and discard any characters different from \n
scanf("%*c"); // read and discard the next char, which, if present, is a \n
请注意,您不能合并上面的 2 个调用,因为它将无法读取前面没有任何其他字符的换行符,因为第一个格式会失败。
关于c - 如何在 OS/X 上的 c 中使用 fflush,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38697428/