Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How do I use getchar() in C correctly?

+1 vote
asked Aug 8, 2019 by Sk1tzFr3n1k (170 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, 2019 by Loki (1,600 points)
selected Aug 8, 2019 by Sk1tzFr3n1k
 
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, 2019 by Sk1tzFr3n1k (170 points)
Thank you much for your help.
commented Aug 9, 2019 by Loki (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.
...