Difference between fflush (stdin) and flushstdin ()

What is the difference between using fflush(stdin) and flushstdin()? The only difference I know is that I need to write this void material before use flushstdin(), but I don't know why.

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();
    }
}

and

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);
    }
}

I'm a newbie! Which code is better? Or are they equal?

+4
source share
3 answers

Both versions have problems.

As already described in detail, it fflush(stdin)has undefined behavior according to the C standard. An alternative that uses a function flushstdin()is not much better. I suggest reading standard input one line at a time and analyzing with sscanf(), all in the utility function, which you can use as needed:

int readfloat(const char *prompt, float *val) {
    char buf[128];
    for (;;) {
        if (prompt) 
            fputs(prompt, stdout);
        if (!fgets(buf, sizeof(buf), stdin)) {
            printf("Premature end of file\n");
            return 1;
        }
        if (sscanf(buf, "%f", val) == 1 && *val > 0)
            return 0;
        printf("Invalid value.\n");
    }
}

int main(void) {
    float a, b, c, s = 0;
    if (readfloat("Enter value of side A: ", &a))
        return 1;
    ...
}
+1
source

, flushstdin C stdin.
fflush - . fflush(stdin); undefined.

c- faq: 12.26a:

fflush . "" , ( ), fflush .

c-faq: 12.26b:

stdio. fflush, fflush(stdin) , . ( stdio fpurge fabort, , .) , stdio : . (, , "y" ), ; . 19.1 19.2. , , , .

+8

. "" , .

fflush C. , stdin, undefined - , C .

fflush . , Linux:

fflush() , , .

fflush(stdin), , Linux , . ; . ( , fflush(stdin) , , , .)

flushstdin - Linux fflush(stdin). EOF ( , ). , .

, , hello ( ), fflush(stdin), .

fflush(stdin), Linux, hello , . "" stdin , , , .

flushstdin() hello, , Enter ( Ctrl-D), . EOF, , .

Again, the behavior is fflush(stdin)not defined by the C standard, so using it makes your program not portable (and your compiler will not necessarily warn you about this).

By the way, “this void material” is a function definition flushstdin. This is not necessary for fflush, because this is a standard C library function that is already defined for you.

+2
source

All Articles