OS/X 如何在 c 中使用 fflush
How to use fflush in c on OS/X
program source code我应该如何在 OS/X 上使用 C 中的 fflush
?当我使用它时,它不会清除我的缓冲区并立即终止程序。
调用 fflush(stdin);
调用未定义的行为。您不应该使用它来 flush 标准输入缓冲区中的字符。相反,您可以读取字符直到下一个换行符并忽略它们:
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 个调用,因为它会无法读取前面没有任何其他字符的换行符,因为第一种格式会失败。
program source code我应该如何在 OS/X 上使用 C 中的 fflush
?当我使用它时,它不会清除我的缓冲区并立即终止程序。
调用 fflush(stdin);
调用未定义的行为。您不应该使用它来 flush 标准输入缓冲区中的字符。相反,您可以读取字符直到下一个换行符并忽略它们:
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 个调用,因为它会无法读取前面没有任何其他字符的换行符,因为第一种格式会失败。