0

Input:

malik
MrJupiter

Output;

malik
malik

I know that fflush(FILE * stream) is used to clear the buffer, but in this example, since the first scanned input is "malik\n" than the buffer (for the first time) is loaded with the String "malik\n" and cleared after the print (that what I think...). In the second iteration, since the buffer is empty (it seems that it isn't empty, because the second output is the same as the first one) the program must return "MrJupiter\n".

Can someone explain to me how the buffer have been manipulated in this case?

#include <stdio.h> 
#include<stdlib.h> 
int main() 
{ 
    char str[20]; 
    int i; 
    for (i = 0; i<2; i++) 
    { 
        scanf("%[^\n]s", str); 
        printf("%s\n", str); 

        // used to clear the buffer 
        // and accept the next string 
        fflush(stdin); 
    } 
    return 0; 
}  
Mr.Jupiter
  • 47
  • 1
  • 7
  • 4
    *"I know that `fflush(FILE * stream)` is used to clear the buffer"* That is *not* defined by the standard. The standard only defined behavior for *output* streams. Whatever book/tutorial is teaching this, burn it. – WhozCraig Jun 15 '19 at 18:39
  • Mr.Jupiter, Why does code not check the return value of `scanf("%[^\n]s", str);`? It certainly would have saved you time. – chux - Reinstate Monica Jun 15 '19 at 20:10

1 Answers1

2

Using fflush on stdin is undefined behavior according to the C standard. Some compilers supports it, but it's not recommended.

I would instead use fgets.

for(int i=0; i<2; i++) {
    if(!fgets(str, 20, stdin)) {
        fprintf(stderr, "Error\n");
        exit(1);
    }

    // No need for \n since fgets includes it
    printf("%s", str);
}
klutt
  • 30,332
  • 17
  • 55
  • 95