Jared Hart Jared Hart - 1 year ago 71
C Question

C Program doesn't wait for user to input a value

I'm new to C, and love learning it so far, however I've come across an issue with my program that I'm having a hard time trying to figure out. In the below program, if the user inputs "1", then they will be prompted to input a "Key", "Age", "First Name", and "Last Name". However, when the user enters "1", the program doesn't wait for the user to enter in a "Key" value, and instead prints straight to "Age".

The output after entering in "1":

Enter the following information:
Key: Age:

The program doesn't wait for the user to enter in a Key value, before asking the user to enter in an Age value. No errors or warnings are occurring when the program is built.

Any and all help is greatly appreciated.

typedef struct userInputsContainer {
char inputOption[2];
char inputKey[2];
char inputAge[3];
char inputFName[10];
char inputLName[10];

int main()
struct userInputsContainer* container = (struct userInputsContainer*)malloc(sizeof(userInputsContainer));

printf("List of options..\n");
printf("1.Create Entry\n2.Search Entries\n");
fgets(container->inputOption, sizeof(container->inputOption), stdin);

if(container->inputOption[0] == '1')
printf("\nEnter the following information.. \n");

printf("Key: ");
fgets(container->inputKey, sizeof(container->inputKey), stdin);
printf("Age: ");
fgets(container->inputAge, sizeof(container->inputAge), stdin);
printf("First Name: ");
fgets(container->inputFName, sizeof(container->inputFName), stdin);
printf("Last Name: ");
fgets(container->inputLName, sizeof(container->inputLName), stdin);

Answer Source

For the very first input, when you read into container->inputOption, the array inputOption have enough space to fit one character and the string terminator. The problem is that fgets typically wants to read the newline after the input as well, and add it to the buffer. If there is no space in the buffer, which is the case here, then fgets will simply not read the newline and leave it in the input buffer. So the next call to fgets will read this newline as the first character, and think it's read the whole line and return without reading anything more.

There are basically two solutions to this problem: The first is to increase the size of the container->inputOption array from two to three characters, so it will fit the newline.

The second solution is to have a loop after the first fgets call which reads and discards characters until it has read the newline.