How do I use getchar() in C correctly?

+2 votes
asked Aug 8 by (180 points)
Here's my code:

#include <stdio.h>
int c1;
int c2;
void choose();
void result();
void main()
{
    choose();
    result();
}
void choose()
{
    printf("Pick 'a', 's', or 'd': ");
    c1 = (char)getchar();
    printf("Pick 'a', 's', or 'd': ");
    c2 = (char)getchar();
}
void result()
{
    printf("You picked '%c' and '%c'.", c1, c2);
}

The first instance of getchar() works correctly.  The second one doesn't wait for user input.  Why's that?  No rush.  Take your time.

1 Answer

+1 vote
answered Aug 8 by (1,600 points)
selected Aug 8 by
 
Best answer

Well what exactly happens is that you enter 2 characters instead to one, one is your character and second is the enter button which gets into the second getchar (c2 = (char)getchar();  this one ) so the quickest work around for this would be to include another getchar() that takes the enter. Use the below edited code:

#include <stdio.h>
int c1;
int c2;
void choose();
void result();
void main()
{
    choose();
    result();
}
void choose()
{
    printf("Pick 'a', 's', or 'd': ");
    c1 = (char)getchar();
    getchar();
    printf("Pick 'a', 's', or 'd': ");
    c2 = (char)getchar();
}
void result()
{
    printf("You picked '%c' and '%c'.", c1, c2);
}

commented Aug 8 by (180 points)
Thank you much for your help.
commented Aug 9 by (1,600 points)
You are welcome .
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...