sk wrote:
.... snip ...
I have the menu printing part down pretty well, but I'm getting an
error where the entire menu will print n+1 number of times when
you input a value with n-digits. I asked around a little, and some
others said that it was because getchar is buffered, and will just
print for every char that is passed. I'm stuck on how to make it
so that the menu will only print once, then ask the use for input.
This is how it is set up right now:
.... snip non-compilable code ...
Can anyone give me any ideas on how to fix this? Sorry if this is
a stupid question. Thanks in advance!
Show us compilable code, and tell us what problems you have with
it. At any rate, the following is an expansion of something I
explained in another thread a few days ago. It compiles, but has
not been tested.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
/* ------------------ */
int skipblanks(FILE *f)
{
int ch;
while (' ' == (ch = getc(f))) continue;
return ch;
} /* skipblanks */
/* ------------------ */
int flushln(FILE *f)
{
int ch;
while (('\n' != (ch = getc(f))) && (EOF != ch)) continue;
return ch;
} /* flushln */
/* ------------------ */
/* Print optional menu and get a single char response. Repeat
as needed until the response is in the acceptable string.
If the first char in acceptable is uppercase, use that as
a default response when a blank line is entered.
Returns response initial char or EOF.
*/
int menuget(const char *prompt, /* whatever prompt is needed */
const char *acceptable) /* list of acceptable ans */
{
int ch;
do {
if (prompt) {
printf("%s", prompt); fflush(stdout);
}
/* Now get a reply */
ch = skipblanks(stdin); /* get first non-blank char */
if ('\n' != ch) flushln(stdin); /* set up to try again */
else if (isupper(acceptable[0])
ch = acceptable[0]; /* 1st is default entry */
} while (!strchr(acceptable, ch) && (EOF != ch));
return ch;
} /* menuget (untested) */
You could call this with something like:
ch = menuget("Enter your desire\n"
" A or a for all\n"
" b for botheration\n"
" x for quit : ",
"Aabx";
Notice the merged strings for the prompt.
--
"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/>