【问题标题】:Fgets skipping inputs [duplicate]Fgets跳过输入[重复]
【发布时间】:2014-12-06 17:40:10
【问题描述】:

我试过环顾四周,但似乎找不到错误所在。我知道这一定与我使用 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++;
    }
}

我的输入是 Joe,是的,Bill,是的,John,不是。如果我使用 scanf 代替第一个 fget,一切都会按计划进行,但我希望能够使用包含空格的全名。我哪里错了?

【问题讨论】:

    标签: c scanf fgets


    【解决方案1】:

    当程序显示Do you have more students to input?,你输入yes,然后在控制台回车,那么\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
    

    【讨论】:

    • 我希望看到:int c; while ((c = getchar()) != EOF &amp;&amp; c != '\n') ;,其中循环体的分号将单独一行。如果用户键入 yes please 或只是在输入的末尾放置一个空格,这可以保护您。在这种情况下,使用int c 而不是char c 至关重要。在原始代码中,您不使用c(所以我的默认编译器选项会抱怨一个设置但未使用的变量;如果我在这里使用代码,我最终会得到(void)getchar();)所以没关系您无法可靠地区分 EOF 和有效字符。
    • @JonathanLeffler:很高兴您对我的帖子提出了改进建议。谢谢 :) 按照您的建议进行了更改。如果用户输入yes ,更新后的更改也将起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    相关资源
    最近更新 更多