I was thinking since the start that why can't fseek(stdin,0,SEEK_SET)
and rewind(stdin)
flush the input buffer since it is clearly written in cplusplusreference
that calling these two functions flush the buffer(Input or Output irrespective).But since the whole idea seemed new,I had put it in a clumsy question yesterday.
And I was skeptical about the answers I got which seemed to suggest I couldn't do it.Frankly,I saw no reason why not.Today I tried it myself and it works!! I mean, to deal with the problem up the newline lurking in stdin
while using multiple scanf()
statments, it seems like I can use fseek(stdin,0,SEEK_SET)
or rewind(stdin)
inplace of the non-portable and UB fflush(stdin)
.
Please tell me if this is a correct approach without any risk.Till now, I had been using the following code to deal with newline in stdin
: while((c = getchar()) != '\n' && c != EOF);
. Here's my code below:
#include <stdio.h>
int main ()
{
int a,b;
char c;
printf("Enter 2 integers\n");
scanf("%d%d",&a,&b);
printf("Enter a character\n");
//rewind(stdin); //Works if activated
fseek(stdin,0,SEEK_SET); //Works fine
scanf("%c",&c); //This scanf() is skipped without fseek() or rewind()
printf("%d,%d,%c",a,b,c);
}
In my program, if I don't use either of fseek(stdin,0,SEEK_SET)
or rewind(stdin)
,the second scanf()
is skipped and newline is always taken up as the character.The problem is solved if I use fseek(stdin,0,SEEK_SET)
or rewind(stdin)
.