C程序跳过fgets

标签 c scanf

<分区>

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

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

#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() 如下:

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

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

关于C程序跳过fgets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20150845/

相关文章:

c - 使用预递增运算符指向指针取消引用的指针

c - 为什么 sscanf 不填充变量?

c - scanf 不等待输入就返回 0

c:使用 scanf() 读取负数

c - 如何使用 -rdynamic 链接器标志?

c - MISRA 是否检查数组索引是否越界?

c - 十一2.如何忽略修饰键事件?

嵌套在 union 内的结构中的通用初始序列 - C 标准中的定义

c - 段错误 : 11 on c program

c - scanf 不接收数据