c - fflush(stdin) 和 flushstdin() 之间的区别

标签 c stdin fflush

使用fflush(stdin)有什么区别 和 flushstdin()?我知道的唯一区别是我需要在使用 flushstdin() 之前编写那些无效的东西,但我不知道为什么。

void flushstdin()
{
    int c;
    while((c = getchar()) != '\n' && c != EOF); 
}
int main () {
    float a, b, c;
    float s=0, ar1=0, ar2=0;
    printf("Inform value of side A");
    while(scanf("%f",&a) != 1 || a <= 0){ 
        printf("Invalid value.\n");
        flushstdin();
    }
}

int main(){
    float a,b,c,s=0;
    printf("Inform value of side A.");
    while(scanf("%f",&a) != 1 || a<=0){
        printf("Invalid value.\n");
        fflush(stdin);
    }
}

我是初学者!哪个代码最好?或者它们是相等的?

最佳答案

区别在于 flushstdin 是用户定义的,并且是标准 C 中刷新 stdin 的唯一方法。
fflush 是一个标准库函数。 fflush(stdin); 将调用未定义的行为。

c- faq: 12.26a :

fflush is defined only for output streams. Since its definition of "flush" is to complete the writing of buffered characters (not to discard them), discarding unread input would not be an analogous meaning for fflush on input streams.

c-faq: 12.26b :

There is no standard way to discard unread characters from a stdio input stream. Some vendors do implement fflush so that fflush(stdin) discards unread characters, although portable programs cannot depend on this. (Some versions of the stdio library implement fpurge or fabort calls which do the same thing, but these aren't standard, either.) Note, too, that flushing stdio input buffers is not necessarily sufficient: unread characters can also accumulate in other, OS-level input buffers. If you're trying to actively discard input (perhaps in anticipation of issuing an unexpected prompt to confirm a destructive action, for which an accidentally-typed "y" could be disastrous), you'll have to use a system-specific technique to detect the presence of typed-ahead input; see questions 19.1 and 19.2. Keep in mind that users can become frustrated if you discard input that happened to be typed too quickly.

关于c - fflush(stdin) 和 flushstdin() 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30675045/

相关文章:

javascript - 是否可以通过 Javascript 迭代 stdin 中的每个单词?

c++ - 如何使用 C++ 找出写入地址的内容?

python - 使用 Python GUI 实时捕获外部 C 程序的输出

c - ANSI C strstr() 不使用指针

c - 如何在 C 中将 stdin 的值存储到数组中?

c++ - 有限制的 cin.ignore 是否继续丢弃新输入?

c - 在等待通过scanf()输入之前,没有通过SSH的输出

windows - 即使系统崩溃也保留 'almost complete'日志

c++ - 什么时候刷新 FILE?

c - 指向字符的指针