【问题标题】:C first fgets() is being skipped while the second runs [duplicate]C 第一个 fgets() 在第二个运行时被跳过[重复]
【发布时间】:2015-06-08 10:46:24
【问题描述】:

问题是:

为什么会跳过第一个 fgets 语句? 我在某处读到这可能是因为我以前使用过的 SCANF() 。 我想弄清楚,但我做不到。 谁能给我解决方案(我可能应该重写代码的第一部分以避免scanf,但是如何?)。

这在我正在努力的代码中:

for(;;)
    {
            //Ask if the user wants to add another CD - Y/N
            fputs("\nWould you like to enter new CDs details?  y or n\n", stdout);
            scanf(" %c" ,&type);
            if (toupper(type) != 'Y')
                break;

            puts("");


            //getting in the album information        
            printf("\tLets enter the details of the CD %d:\n\n", count + 1);


            fputs("Title?\n", stdout);   

            //this fgets statement is being skipped
            fgets(title[count], sizeof title[count], stdin);
            title[count][strlen(title[count]) - 1] = '\0';

            fputs("Atrist? \n", stdout);
            fgets(artist[count], sizeof artist[count], stdin);
            artist[count][strlen(artist[count]) - 1] = '\0';
    }

【问题讨论】:

  • 不要混用 scanf()fgets()。仅使用 fgets() 进行用户输入。

标签: c fgets


【解决方案1】:

这是因为最后一个ENTER 按键导致newline 留在输入缓冲区中。这是由第一个fgets() 拾取的。

您可以在第一个 fegts() 之前添加 while(getchar() != '\n'); 以避免这种情况。

[编辑: 或者,为了更好,正如 Chux 在下面的评论中提到的那样,感谢他,使用类似

int ch; while((ch = getchar()) != '\n' && ch != EOF);

处理“换行符”以及EOF。]

也就是说,混合使用scanf()fgets() 绝不是一个好的选择。始终使用fgets(),这是可能的,而且更好。

【讨论】:

  • 也许int ch; while((ch = getchar()) != '\n' && ch != EOF); 可以防止while(getchar() != '\n'); 在文件末尾无限循环。
  • @chux 完成,更新。 :-)
【解决方案2】:

是的,这是因为您的scanf() 没有读取多个字符,但用户按下了回车键。返回值保留在输入缓冲区中,因此fgets() 立即看到并返回。

不要混合使用,只使用fgets()

【讨论】:

    【解决方案3】:

    简单的改变

    scanf(" %c" ,&type);
    

    scanf(" %c%*c" ,&type);
    

    第一个fgets 被跳过的原因是您的scanfstdin 中留下了换行符。 fgets 看到这个字符并使用它,因此不等待进一步的输入。

    %*c 告诉scanf 读取并丢弃一个字符。

    【讨论】:

    • 谢谢大家!非常有用的提示。下次我会更仔细地浏览论坛!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多