C程序不等待用户输入值

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

我是 C 的新手,到目前为止我很喜欢学习它,但是我在我的程序中遇到了一个问题,我很难弄清楚。在下面的程序中,如果用户输入“1”,则会提示他们输入"Key"、"Age"、"First Name"和"Last Name"。但是,当用户输入“1”时,程序不会等待用户输入 "Key" 值,而是直接打印到 "Age".

输入“1”后的输出:

输入以下信息: 关键:年龄:

在要求用户输入年龄值之前,程序不会等待用户输入键值。构建程序时没有出现错误或警告。

非常感谢任何帮助。

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

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);
    }
}

对于第一个输入,当您读入 container->inputOption 时,数组 inputOption 有足够的 space 来容纳一个字符和字符串终止符。问题是 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 会将此换行符作为第一个字符读取,并认为它已读取整行,而 return 不会再读取任何内容。

这个问题基本上有两个解决方案:第一个是将 container->inputOption 数组的大小从两个字符增加到三个字符,以便它适合换行符。

第二个解决方案是在第一个 fgets 调用之后有一个循环,该循环读取并丢弃字符,直到读取换行符。