为什么我无法使用fgets填充的while循环打印数组?

时间:2014-09-30 04:10:41

标签: c

main()
{       
    FILE *fp;       
    char buff[255];      
    int i;    
    fp = fopen("input.txt", "r");    
    if( fp != NULL )      
    {         
       while ( !feof(fp ) )    
        {
         memset(buff, '\0', sizeof( buff) );
         fgets(buff, 255, (FILE*)fp);
        }
       fclose(fp);
     }       
    i=0;    
    while(  buff[i]!='\0' )    
    {           
       printf ("%s",buff[i]);
       i++;    
    }    
}

3 个答案:

答案 0 :(得分:1)

评论包含while循环while ( !feof(fp ) )的行,并将%s替换为%c中的printf

答案 1 :(得分:0)

printf ("%s",buff[i]);

应该是

printf ("%c",buff[i]);

还有更好的方法是

char buffer[255];
while(!feof(fp)) {
    if (fgets(buffer,255,fp)) {
        printf("%s\n", buffer);
    }
}

答案 2 :(得分:0)

fgets can be used as below and also you need to use %c instead of %s



 int main()
    {

       FILE *fp;

       char buff[255];

       int i;


       fp = fopen("input.txt", "r");

       if( fp != NULL )
       {   
          while(!feof(fp))
          {   
             memset(buff, '\0', sizeof( buff) );
             fgets(buff, 255, (FILE*)fp);
             puts(buff);
          }   
          fclose(fp);
       }   

       return 0;

    }