Flushing stdin (was: Re: gcc problem?)
Eric R. Krause
ekraus02@baker.edu
Sun Nov 24 13:26:00 GMT 2002
Carlo,
Visual C++ 6.0 CRT (and AFAICT, that of Visual C++.NET too) allow you to
flush an input stream. The only problem with that is that the C standard
apparently defines flushing ONLY for output streams (sec. 7.9.5.2). Why in
the hell MicroSquash didn't disclose that this behavior was M$-specific, who
knows--it's yet another way they try to lock you into their software.
For reading words entered by the user, I'd approach the situation using
fgets() and a pair of string buffers--one to hold the input line and one to
hold the word that is sscanf()'ed. After we've read the word, we can
loop-read until there are no more characters on stdin (in case we entered
past the size of the string buffer), knowing that our word is in a separate
buffer and that each iteration both are NULLed out.
Here's the code...
#include <string.h>
#include <stdio.h>
int main() {
char string[80];
char word[80]; /* extra string buffer */
int i;
for (i = 0; i < 2; i++) {
memset(string, 0, 80 * sizeof(char));
memset(word, 0, 80 * sizeof(char));
printf("Enter some words: ");
fgets(string, 80, stdin); /* see note A */
sscanf(string, "%s", word);
printf("The first word you entered was... %s\n", word);
while (!strchr(string, '\n'))
fgets(string, 80, stdin);
}
return 0;
}
Note A:
Pressing Enter as soon as the prompt comes up will cause fgets() to write a
newline and a NULL to the buffer and return. If you want to FORCE the user
to enter a non-blank line, then change
fgets(string, 80, stdin);
to
do {
fgets(string, 80, stdin);
} while (string[0] == '\n');
---
Eric R. Krause
--
Unsubscribe info: http://cygwin.com/ml/#unsubscribe-simple
Bug reporting: http://cygwin.com/bugs.html
Documentation: http://cygwin.com/docs.html
FAQ: http://cygwin.com/faq/
More information about the Cygwin
mailing list