Hi Guys,
I wasn't expecting so many replys on this one:
I will post my question again to focus on my problem.
I am looking for an efficient way to flush stdin (IN C) to avoid the following known problem:
Code:
scanf("%d",&num);
fgets(buf,80,stdin);
scanf() will take the number and leave newline in the stream so fgets() will not wait for the user input.
"The function fflush forces a write of all user-space buffered data for the given OUTPUT or update stream via the stream's underlying write function. The open status of the stream is unaffected. If the stream argument is NULL, fflush flushes all open output streams."
The behaviour of fflush() for stdin is undefined! and should not be used for input.
So this one is not an option.
The second option I could use is:
Code:
while ((c = getchar()) != '\n' && c != EOF);
This will clear the buffer, but if there is no data in the input stream, we will have to wait until there is, which is again undesirable, so this is not an option too.
My 3rd option was not to mix fgets and scanf, so I came up with the following code:
Code:
int main(void)
{
char cNum[10];
int iNum=0;
char cStr[20];
puts("Enter a number:");
fgets(cNum,10,stdin);
sscanf(cNum,"%d",&iNum);
puts("Enter a string:");
fgets(cStr,20,stdin);
printf("Num=%d\n",iNum);
puts(cStr);
return 0;
}
Everything works fine until the size of the input is bigger than the size of the array. In this case the results are the same as:
Code:
scanf("%d",&num);
fgets(buf,80,stdin);
So this one is not an option eigher.
There must be an ANSI solution for this, it is impossible that C ANSI don't give this basic option and forcing me to hack the most basic operation of user input.
Please guys guide me here, I am running out of options and it is driving me CRAZY!
Thanks a million
Salvador