gpt4 book ai didi

c - fflush 是如何工作的?

转载 作者:太空宇宙 更新时间:2023-11-04 00:35:48 26 4
gpt4 key购买 nike

我不确定我是否正确理解了 C 中刷新的工作原理。我就是无法按照多本手册和引用书中的描述让它工作。这是一个带有注释的示例:

#include <stdio.h>


int main(void) {
int x;
char ch;

printf("Prompt: ");
scanf("%d", &x); /* I key in 67 and press Enter. At this very moment,
the input buffer should contain the ASCII codes
for the numbers 6 and 7 as well as the ASCII code
for the newline character, which is 10. The scanf
function is going to find the ASCII codes for 6
and 7, convert them to the integer 67, assign it
to the variable x and remove them from the
buffer. At this point, what still remains in the
buffer is the newline character. */
fflush(stdin); /* I want to do some more input. So, I flush the
buffer to remove anything that still might be
there, but it doesn't really look like fflush is
doing that. */

printf("Prompt: "); /* I'm not going to be able to get my hands on
the following line of code because fflush is
not doing its job properly. The remaining
newline character is going to be read into the
variable ch automatically, thus not allowing
me to enter anything from the keyboard. */
scanf("%c", &ch);

printf("x: %d, ch: %d\n", x, ch);
/*
OUTPUT:
Prompt: 67
Prompt: x: 67, ch: 10
*/


return 0;
}

最佳答案

不要执行 fflush(stdin);,它会调用 undefined behavior .

引用C11

Ifstream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

stdin 不是输出流。

关于c - fflush 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37269602/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com