Hey all,
I could really use a few viewpoints on using the fflush() function. I'm just starting out with C, and I'm currently going through C in 21 Days.
The book states the following:
There is a second way in which you can clear the extra characters that were typed in. The fflush() function flushes the information in a stream--including the standard input stream. fflush() is generally used with disk files (which are covered on Day 16); however, it can also be used to make Listing 14.7 even simpler.
Now, the following, is the code that I typed up from the book, to try to use the fflush function, to demonstrate the clearing of stdin:
Code:
/* flush.c - Clearing stdin of extra characters, using fflush() */
#include <stdio.h>
main()
{
int age;
char name[20];
puts("Enter your age.");
scanf("%d", &age);
/* Clear stdin of any extra characters. */
int test = fflush(stdin);
puts("Enter your first name.");
scanf("%s", name);
printf("Your age is %d.\n", age);
printf("Your name is %s.\n", name);
printf("%d", test);
return 0;
}
After compiling, I don't get any errors (this is with gcc (dgjpp) on win32). Now, here's what I get after running the program from a DOS window:
(with correct input)
Code:
Enter your age.
22
Enter your first name.
John
Your age is 22.
Your name is John.
(with incorrect input)
Code:
Enter your age.
22 and margh
Enter your first name.
John
Your age is 22.
Your name is and.
I remember reading somewhere that perhaps this was a compiler issue, so I compiled the same program, with lcc, which is a full-on win32 compiler, and not command line, and after running the program, it worked...
However, and this is where I'm not very confused, I talked to a guy on a newsgroup about this, and here's what he's saying:
Oh dear. No, it is NOT a gcc problem. It is a problem with your BOOK, which has failed to explain to you that some constructs are illegal in C, and that your use of such constructs breaks the contract between you and the implementation. If you break the rules, the compiler is allowed to break the rules too. Using fflush(stdin) breaks the rules. gcc chooses not to play the game by your new rules. lcc /seems/ to play the game, but you have no guarantees that lcc doesn't do something weird under the hood, without telling you.
Can someone clarify whether I should be using fflush(stdin) at all?
Thanks in advance (sorry it's long, I wanted to show the route I've taken so far),
John.