Function fgets skips user input?

Viewed 2335

When I use the function fgets, the program skips the user input, effecting the rest of the program. An example program with this effect is:

#include <stdio.h>

int main() {
    char firstDigit[2];
    char secondDigit[2];

    printf("Enter your first digit: ");
    fgets(firstDigit, 1, stdin);
    printf("\nEnter your second digit: ");
    fgets(secondDigit, 1, stdin);
    printf("\n\nYour first digit is %s and your second digit is %s.\n", firstDigit, secondDigit);
}

I then thought that maybe the problem was that fgets might be writing the newline, so I changed the code to account for that:

#include <stdio.h>

int main() {
    char firstDigit[3];
    char secondDigit[3];

    printf("Enter your first digit: ");
    fgets(firstDigit, 2, stdin);
    printf("\nEnter your second digit: ");
    fgets(secondDigit, 2, stdin);
    printf("\n\nYour first digit is %c and your second digit is %c.\n", firstDigit[0], secondDigit[0]);
}

This time, the first input works properly, but the second input is skipped.

What am I doing incorrectly?

3 Answers
Related