Fget跳过输入 [英] Fgets skipping inputs

查看:80
本文介绍了Fget跳过输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've tried looking around and I can't seem to find where the error lies. I know it must have something to do with the way I used fgets but I can't figure out for the life of me what it is. I've read that mixing fgets and scanf can produce errors so I've even changed my second scanf to fgets and it still skips the rest of my inputs and only prints the first.

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,一切都会按计划进行,但是我希望能够使用包含空格的全名.我要去哪里错了?

My inputs are Joe, yes, Bill, yes, John, no. All goes according to plan if I utilize scanf in lieu of the first fgets but I would like be able to use full names with spaces included. Where am I going wrong?

推荐答案

程序显示是否有更多学生要输入?,然后输入 yes ,然后按在控制台上输入,然后 \ n 将存储在输入流中.

When the program displays Do you have more students to input? and you input yes and then hit enter on console, then \n will be stored in input stream.

您需要从输入流中删除 \ n .为此,只需调用 getchar()函数.

You need to remove the \n from the input stream. To do that simply call getchar() function.

如果您不混合使用 scanf fgets ,那会很好. scanf 有很多问题,最好使用 fgets .

It will be good if you don't mix scanf and fgets. scanf has lots of problems, better use fgets.

为什么每个人都说不使用scanf?我应该改用什么呢?

尝试以下示例:

#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

这篇关于Fget跳过输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆