C 程序跳过 fgets [英] C program skips fgets

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

问题描述

我的程序编译正常,但是当它调用 getinput() 函数时,它从不提示输入.

My program compiles ok but it when it calls the getinput() function it never prompts for input.

编辑以显示更多代码,我添加了 fflush 但由于某种原因它仍然跳过它.

Edited to show more code, I added fflush but it still skips it for some reason.

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


main(){

    char mystring[] = "It's equal to it. ";
    int k = 32;
    int e;
    printf("Enter a number: ");
    scanf("%d",&e);
    if(e == k){
        printf("\n\n%s\n",mystring);

    } else if(e < k){
        printf("\n\n%d\n",e);

    } else {


        getinput();
    }

    exit(0);

}

int getinput(){

    char gettext[64];

    printf("Enter text here: ");
    fflush(stdout);
    fgets(gettext, 64, stdin);
    printf("\n\nYou entered: %s\n\n",gettext);
    return 0;


}

推荐答案

在这行 scanf("%d",&e) 之后添加一个 getchar()像这样:

after this line scanf("%d",&e) add a getchar() like this :

scanf("%d",&e);
getchar();

当您按下 Enter 时,换行符会保留在缓冲区中,因此当 fgets 被调用时,换行符会传递给它,就像您按下 Enter 一样

when you press Enter the newline character stays in the buffer so when fgets is called the newline is passed to it and it actes as if you pressed Enter

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

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