Input problem with getchar()

Joined
Aug 14, 2006
Messages
1
Reaction score
0
I've been learning C for the past few weeks, but I've noticed that whenever I use the getchar() function that it reads both the character and enter. For example, when I use the switch case loop, it does both the case I chose, plus the default case (since I usually done have a case for a newline). Heres an example code.

char c;
int done=0;
while(!done)
{
c = getchar();
switch(c)
{
case 'a':
printf("You chose A");
default:
printf("Sorry, invalid option");
}
}

If I were to type a, it would print "You chose A", then it would print "Sorry, invalid option). Is there any way to fix this? Is this related to my operating system settings? I'm using Windows XP, by the way.

Yes, I have also tried using fflush(stdin), but it still seems to include the newline character (or whatever enter does) into the getchar().
 
Joined
Sep 6, 2006
Messages
2
Reaction score
0
I think you forgot to use the break statement in the case
When you use switch in C, each "case" must have a break to avoid the rest "cases" be processed as well
Summarizing, the problem is in the switch sentence, not in the getchar

-----------------------
http://www.uberum.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top