fgets()不能按预期运行 [英] fgets() doesn't function as expected

查看:76
本文介绍了fgets()不能按预期运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码

int main(){
   int N,i,radius,diameter,count =0;
   char str[20];
   char color[N][20];
   printf("Get the num : ");
   scanf("%d",&N);

   printf("Enter the mesage\n");
   for(i=0;i<N;i++){
      fgets(color[i],20,stdin);
   }
   for(i=0;i<N;i++){
      printf("%s",color[i]);
  }
  return 0;
}

输入为:

N = 3
red 50,
50 green,
blue 50

这里的问题是,如果N为3,则for循环内的fgets仅执行两次.如果我注释scanf语句,则不会出现此问题.有人可以解释一下导致此问题的原因以及如何解决该问题吗?

Here the problem is fgets inside for loop gets executed only twice if N is 3. This problem doesn't arise if I comment the scanf statement. Can somebody explain me what is causing this problem and how it can be solved?

推荐答案

几个小时后,我意识到:

After a few hours of scratching my head, I realized the following:

  • 避免使用scanf.管理缓冲区溢出并不容易.
  • 始终尝试使用fgets获取用户输入.

在此处尝试此代码:

#include<stdio.h>
#include<stdlib.h>
int main(){
   int N,i,radius,diameter,count =0;
   char str[20];

   printf("Get the num : ");

   char buffer[64];
   fgets(buffer, 64, stdin);
   N = strtoul(buffer,NULL,10); 
   char color[N][20];

   printf("%d\n",sizeof(color));

   printf("Enter the mesage\n");

   for(i=0;i<N;i++){
      fgets(color[i],20,stdin);
      if(color[i][strlen(color[i])-1]=='\n'){

     color[i][strlen(color[i])-1]='\0';
  }
  else{

     while((getchar())!='\n');//this is just to prevent an overflow for the size of char arrays
  }

   }
   for(i=0;i<N;i++){
      printf("%s\n",color[i]);
  }
  return 0;
}

请注意,我首先在char数组中输入了一个数字.使用strtoul(将字符串转换为无符号长整数)将其转换为数字.现在,在for循环中,我再次使用fgets进行输入.问题是,如果输入的字符串大于19个字符,其余部分将留在输入缓冲区内,并应分配给后续输入.为了管理这一点,我在while循环中使用了getchar,该循环消耗了输入流中所有不必要的字符和换行符.避免使用fflush,因为它可能导致未定义的行为,如此处回答

Notice that I first input a number inside a char array. Convert that into a number using strtoul(string to unsigned long). Now inside the for loop I again use fgets to take inputs. The problem was, if you enter a string greater than 19 chars, the remaining part will be left inside the input buffer and shall be assigned to the subsequent input. To manage that I used getchar inside a while loop, which consumes all the unnecessary characters and the newline character from the input stream. Avoid using fflush as it may result in undefined behavior as answered here

- fflush(stdin)函数不起作用

- http://www.geeksforgeeks.org/clearing -the-input-buffer-in-cc/

还请注意,您正在使用可变长度数组,这可能并不总是一个不错的选择.较旧的c编译器版本禁止使用它们.您在初始化N之前先声明了color [N] [20].那是错误的.

Also note that you are using Variable Length Arrays which may not always be a good choice. Older versions of c compiler prohibit them. You had declared color[N][20] first before initializing N. That was wrong.

我建议您也阅读此书

- C-scanf()vs gets()vs fgets()

这篇关于fgets()不能按预期运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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