C:当要求用户提供2个输入时,第二个问题将不会提示输入要存储在变量中

时间:2020-09-21 10:45:17

标签: c scanf fgets

如果我一次尝试成绩或全名,我会得到预期的结果

"Enter your Grade: "
"Your grade is x"

"Enter your full name:"
"Your full name is xxxx  xxxx"

如果我在打印输出下面运行

Enter your Grade:2
Your grade is 2
Enter your full name:  Your full name is

我不知道为什么没有提示我进行第二次输入,特别是因为我知道在单独尝试时它可以工作* /

int main()
{

    char grade;
    printf("Enter your Grade: ");
    scanf("%c", &grade);
    printf("Your grade is %c \n", grade);



    char fullName[20];
    printf("Enter your full name:  ");
    fgets(fullName, 20, stdin); /*2nd argument specify limits of inputs*, 3rd means standard input ie command console */
    printf("Your full name is %s \n", fullName);



    return 0;
}

3 个答案:

答案 0 :(得分:1)

请勿将scanf()fgets()混合-在这种情况下,缓冲区中存在的,由scanf()保持不变的换行符将被馈送到fget()并赢得“ t”询问任何新输入。

最好在所有用户输入中使用fgets()

答案 1 :(得分:1)

scanf("%c");缓冲区问题,%c将只吃一个字符,因此 \n将保留在缓冲区中以便下一个字符读取。

尝试一下

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char grade;
    printf("Enter your Grade: ");
    scanf("%c", &grade);
    getchar(); // here
    printf("Your grade is %c \n", grade);

    char fullName[20];
    printf("Enter your full name:  ");
    fgets(fullName, 20, stdin); /*2nd argument specify limits of inputs*, 3rd means standard input ie command console */
    printf("Your full name is %s \n", fullName);

    return 0;
}

使用getchar();在缓冲区中占用多余的字符。

答案 2 :(得分:0)

问题出在此行scanf("%c", &grade);上,每次使用scanf()时,请切记enter键将存储在缓冲区中。由于enter键位于缓冲区中,因此在执行fullName时它会直接进入fgets(fullName, 20, stdin);。这样就可以得到输出:

Enter your Grade:2    
Your grade is 2
Enter your full name:  Your full name is

您可以通过在getchar();之后立即使用getch();scanf();来捕获Enter键,并确保fullName获得正确的输入来解决问题。解决该问题的另一种方法是使用fflush(stdin);。它们基本上执行相同的操作,但是fflush(stdin);从缓冲区中清除了Enter键。因此,应在fflush(stdin);之后使用scanf();清除Enter

留下的不需要的scanf();

这是一个很长的过程,需要很多帮助,但我希望此信息对您有帮助:)))

相关问题