【问题标题】:why is fgets() function not prompting user for input the second time? [duplicate]为什么 fgets() 函数没有第二次提示用户输入? [复制]
【发布时间】:2021-03-02 22:03:25
【问题描述】:

代码是:

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

        int main (void)
        {
            char ch,str[100],sen[100];
            printf("enter the string : ");
            fgets(str,sizeof(str),stdin);
            printf("enter the character : ");
            scanf("%c",&ch);
            printf("enter  the sentence : ");
            fgets(sen,sizeof(sen),stdin);
            printf("character is : %c\n",ch);
            printf("string is : %s\n",str);
            printf("sentence is : %s",sen);
            return 0;
        }

这就是我希望我的程序工作的方式: 输入:

    enter the string : abcde
    enter the character : k
    enter the sentence : i am a beginner.

输出:

    character is : k
    string is : abcde
    sentence is : i am a beginner.

这就是它的结果:

    enter the string : abcde
    enter the character : k
    enter  the sentence : character is : k
    string is : abcde
    
    sentence is :

这个程序没有提示用户输入句子。 请告诉我为什么这个fgets() 函数不能正常工作。

【问题讨论】:

  • fgets() 仅用于阅读内容。因此它不会提示任何事情。
  • scanf("%c",&amp;ch); 只读取一个字符。如果输入换行符,它将在缓冲区中留下换行符,并且换行符将被fgets()消耗掉。
  • 在 scanf 之后调用 getchar() 以消耗缓冲区中剩余的换行符。

标签: c string input fgets


【解决方案1】:

fgets 工作正常。您不刷新标准输出,因此 printf 将数据写入内部缓冲区,但在读取 fgets 块之前不会产生任何实际输出。只需在 printfs 后添加fflush(stdout)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-26
    • 2013-12-04
    • 2022-01-10
    • 2021-10-08
    • 2012-05-11
    • 2015-04-24
    • 1970-01-01
    • 2015-05-20
    相关资源
    最近更新 更多