【问题标题】:C fgets skips user input, even when flushing buffer即使在刷新缓冲区时,C fgets 也会跳过用户输入
【发布时间】:2017-03-04 16:12:22
【问题描述】:

我正在尝试从用户那里获取输入,而 fgets 正在跳过第一个输入。我知道原因是 fgets 正在读取上一条语句中的“\n”,或者至少我认为这是原因,但我似乎无法修复它

请注意,这是一个更大项目的一部分

 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #define MAX 1000

 int main(void) {

  char  content[MAX];
  char  content2[MAX];
  char  content3[MAX];
  char  content4[MAX];
  char  content5[MAX];
  char  input[4];
  char  input2[4];

  printf("Do you want to continue yes/no?\n");
  fgets(input, 4, stdin);

  if (strncmp (input, "no", 2) == 0) {
     break;
  }
  else if (strncmp (input, "yes", 3) == 0) {
  fflush(stdin);

     printf("Country:\n");
     fgets(content, MAX, stdin);

     printf("Province/state: \n");
     fgets(content2 ,MAX, stdin);

     printf("Postal/zip code:\n");
     fgets(content3 ,MAX, stdin);

     printf("Company:\n");
     fgets(content4 ,MAX, stdin);

     printf("Email:\n");
     fgets(content5 ,MAX, stdin);
  }

【问题讨论】:

  • 这正是正在发生的事情。最简单的解决方法是增加input 的大小。您希望 that 调用 fgets 在 yes/no 末尾选择换行符

标签: c string input buffer fgets


【解决方案1】:

"yes" 加上终止空字符占用 4 个字节,因此 '\n' 保留在缓冲区中。为input 分配更多缓冲区并将其新长度传递给fgets(),以便读取yes 而不会在流中留下换行符。

还要注意fflush(stdin); 调用未定义的行为,所以你不应该使用它。

【讨论】:

  • 非常感谢您的完美运行!顺便说一句,我知道这与问题无关,但是您对我应该使用什么而不是 fflush 有个人建议吗?
【解决方案2】:
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #define MAX 1000

 int main(void) {

  char  content[MAX];
  char  content2[MAX];
  char  content3[MAX];
  char  content4[MAX];
  char  content5[MAX];
  char  input[4];
  char  input2[4];

  printf("Do you want to continue yes/no?\n");
  fgets(input, 4, stdin);

  if (strncmp (input, "no", 2) == 0) {
     exit(0);
  }
  else if (strncmp (input, "yes", 3) == 0) {
  fflush(stdin);//this is not portable
  while(getchar()!='\n');//this thing works
     printf("Country:\n");
     fgets(content, MAX, stdin);

     printf("Province/state: \n");
     fgets(content2 ,MAX, stdin);

     printf("Postal/zip code:\n");
     fgets(content3 ,MAX, stdin);

     printf("Company:\n");
     fgets(content4 ,MAX, stdin);

     printf("Email:\n");
     fgets(content5 ,MAX, stdin);
  }
 }

fflush() 在大多数情况下都不起作用。请改用以下代码

while(getchar()!='\n');

【讨论】:

    【解决方案3】:

    您是否尝试在 fflush 中添加 stdin?你应该有这样的东西:

    fflush(stdin);

    【讨论】:

    • 不,你不应该。在输入流上调用 fflush 具有未定义的行为。这是一个糟糕的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 2017-07-14
    • 2016-12-10
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多