You are not logged in.
I'm quite new to C. I'm trying to put together a simple menu (in console), where the program presents a few choices, the user enters a choice, and is then prompted for further information. What I have is this:
int main ()
{
char selection;
char data;
while (selection != 'q') {
printf ("MAIN MENU\n\n");
printf ("a\nb\nc\n");
printf ("Enter choice: ");
scanf ("%c", &selection);
switch (selection) {
case 'a':
printf ("Enter a: " );
scanf ("%c", &data);
break;
case 'b':
printf ("Enter b: " );
scanf ("%c", &data);
break;
case 'c':
printf ("Enter c: " );
scanf ("%c", &data);
break;
default:
printf ("Default.\n");
break;
}
printf ("You entered %c.\n\n", data);
}
printf ("\nGoodbye.\n\n");
}
What I want is this:
$ ./a.out
MAIN MENU
a
b
c
Enter choice: a
Enter a: A
You entered A.
MAIN MENU
a
b
c
Enter choice: q
Goodbye.
What I get is this:
$ ./a.out
MAIN MENU
a
b
c
Enter choice: a
Enter a: You entered
.
MAIN MENU
a
b
c
Enter choice: q
Goodbye.
I don't understand why it's looping through again after executing the case's printf () but before the case's scanf () statement. I assume there's some nuance of either switch(), printf(), or scanf() to which I'm not yet privy. Or maybe some really, really dumb newbie mistake. Can anyone enlighten me?
(PS: It's not homework, even though it probably looks like it. I threw together this simple example rather than edit the code of the actual project.)
Thanks!
Last edited by ibrunton (2011-07-08 02:09:24)
Offline
Well, scanf is eating up the first character you type, but leaves the newline in the buffer. Thus, when scanf is called the second time, it just eats up the newline and its job is done.
scanf("%1s", &selection) might do the job. So long as the user only types one character and then a newline, I think.
A better solution, I think, would be to use getchar instead and explicitly gobble up the newlines. I dunno.
Offline
Ah. I forgot about the newlines. (Like I said, dumb newbie mistake!) I'll try getchar.
Offline
scanf("%1s", &selection) might do the job.
Do NOT do this, because it'll write '\0' to *(&selection + 1), which is a random location somewhere on your stack.
Offline
Guff wrote:scanf("%1s", &selection) might do the job.
Do NOT do this, because it'll write '\0' to *(&selection + 1), which is a random location somewhere on your stack.
Glad I didn't try that one, then. After some googling and man pages, I ended up using this (putting it here in case it happens to help anyone else in the future):
int input;
char selection;
while ((input = getchar ()) != "\n")
selection = (char)input;
Worked like a charm every time.
Offline