首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Fgets跳过输入

Fgets跳过输入
EN

Stack Overflow用户
提问于 2014-10-12 03:11:09
回答 1查看 10.6K关注 0票数 4

我试着四处看看,但似乎找不到错误所在。我知道这一定与我使用fgets的方式有关,但我无论如何也搞不清楚它是什么。我读到混用fgets和scanf会产生错误,因此我甚至将第二个scanf更改为fgets,但它仍然跳过其余的输入,只打印第一个。

代码语言:javascript
复制
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代替第一个fgets,一切都按计划进行,但我希望能够使用包含空格的全名。我哪里错了?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-12 03:15:57

当程序显示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?

试一下这个例子:

代码语言:javascript
复制
#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
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26318275

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档