Why doesn't my program wait for another input?

58 Views Asked by At

I've written a small program to practice getting user input using getchar() and outputting it using putchar() in C.

What I want my program to do: I want the program to ask the user to enter a char, store it in a char variable, and print it out. And then I want it to ask the user to enter another char, store it in another char variable, and print it out.

The following is my code:

#include <stdio.h>

int main()
{
    printf("Please enter a char: ");
    char myChar = getchar();
    printf("The char entered is: ");
    putchar(myChar);
    printf("\n"); 

    printf("Please enter another char: ");
    char myChar2 = getchar();
    printf("The char entered is: ");
    putchar(myChar2);
    printf("\n");

    return 0;
}

When I run this program in my Terminal, the following is what I see, which is not how I expect it to behave.

cnewbie@cnewbies-MacBook-Pro c % ./a.out
Please enter a char: k
The char entered is: k
Please enter another char: The char entered is: 

cnewbie@cnewbies-MacBook-Pro c % 

When I run the program, it outputs "Please enter a char: " and waits for me to enter a char. I type k and hit return. Then it outputs not only "The car entered is: k" but also the other lines shown above all at once.

Question: Why doesn't my program wait for me to input another char?

I'm a beginner in C and I have no clue why this is behaving this way. Please help!!

1

There are 1 best solutions below

0
On

getchar also reads white space characters including the new line character '\n' that is placed in the input buffer due to pressing the Enter key.

Instead use a call of scanf the following way

char myChar;
scanf( " %c", &myChar );
       ^^^^

Pay attention to the leading space in the format string. It allows to skip white space characters.