Fgets跳过输入

时间:2014-10-11 19:11:09

标签: c scanf fgets

我试过环顾四周,似乎无法找到错误所在。我知道它必须与我使用fgets的方式有关但我无法弄清楚它的生命是什么。我已经读过混合fgets和scanf会产生错误,所以我甚至将我的第二个scanf更改为fgets,它仍然会跳过其余的输入,只打印第一个。

int addstudents = 1;
char name[20];
char morestudents[4];

for (students = 0; students<addstudents; students++)
{
    printf("Please input student name\n");
    fgets(name, 20, stdin);
    printf("%s\n", name);
    printf("Do you have more students to input?\n");
    scanf("%s", morestudents);
    if (strcmp(morestudents, "yes")==0)
    {
    addstudents++;
    }
}

我的投入是乔,是的,比尔,是的,约翰,不。如果我使用scanf代替第一个fgets,所有都按计划进行,但我希望能够使用包含空格的全名。我哪里错了?

1 个答案:

答案 0 :(得分:6)

当程序显示Do you have more students to input?并输入yes然后按控制台上的Enter键时,\n将存储在输入流中。

您需要从输入流中删除\n。要做到这一点,只需调用getchar()函数。

如果你不混合scanffgets,那就太好了。 scanf有很多问题,请更好地使用fgets

Why does everyone say not to use scanf? What should I use instead?

试试这个例子:

#include <stdio.h>
#include <string.h>
int main (void)
{
    int addstudents = 1;
    char name[20];
    char morestudents[4];
    int students, c;
    char *p;
    for (students = 0; students<addstudents; students++)
    {
        printf("Please input student name\n");
        fgets(name, 20, stdin);
        //Remove `\n` from the name.
        if ((p=strchr(name, '\n')) != NULL)
            *p = '\0';
        printf("%s\n", name);
        printf("Do you have more students to input?\n");
        scanf(" %s", morestudents);
        if (strcmp(morestudents, "yes")==0)
        {
            addstudents++;
        }
        //Remove the \n from input stream
        while ( (c = getchar()) != '\n' && c != EOF );
    }
    return 0;
}//end main