Flash said:
blufox said:
This is a simple code snippet i used ...
#include <stdio.h>
int main(void)
{
int ch;
do {
printf("still yes...\n");
printf("\nenter choice :: ");
fflush(stdout);
/* Otherwise there is no guarantee the output will be displayed
before waiting for input. Never heard of line buffering? */
ch = getchar();
}while(ch == 'y');
return 0;
}
Output ::
[rautela@blufox c]$ ./a.out
still yes...
enter choice :: y
still yes...
[rautela@blufox c]$
Why didn't it waits for my input the next time?
I am compiling this on a Fedora Core 5 using gcc 4.1.
Am i missing something here?
Yes. How many keys did you press at the first prompt? I'll bet it was
more than one...
Generally it is better to use fgets (not gets, NEVER gets) to read a
complete line and then process it. It is far simpler to get it right
that way.
Using fgets or the equivalent requires a buffer, and checking for
line completion etc. A more positive way is to insist on an
'enter' as a response to the wait, and handle it with a call to:
flushln(stdin);
in place of the getchar() call. The flushln routine will be useful
in many places, and should be:
int flushln(FILE *f) {
int ch;
while ((EOF != (ch = getc(f))) && (ch != '\n')) continue;
return ch;
}
No buffer, or other storage is required. Now, if you want a
specific single non-blank character response, you can use:
int getreply(FILE *f) {
int ch;
while (' ' == (ch = getc(f))) continue;
if ('\n' != ch) flushln(f);
return ch;
}
Note that all these things can return EOF. A few such routines in
your toolbox go a long ways to keeping interactive input clean.
The routines are more useful when the input file is parametized.
Note that getc(stdin) is equivalent to getchar().
--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <
http://cfaj.freeshell.org/google/>
Also see <
http://www.safalra.com/special/googlegroupsreply/>