如何对存储在c

时间:2015-08-20 06:28:32

标签: c sorting

在这些代码的帮助下,我能够获取数据但无法对其进行排序。我的问题是如何对文件中的数据进行排序我没有得到它的逻辑。我可以检索数据但无法对其进行排序。

对于Ex。文件数据:

john,
ash,
billy,
doe

预期产出:

ash,
billy,
doe,
john

我的工作:

int main ( void )
{
    FILE *file = fopen ( "college.text", "r" );
    int i, j;

    char arra[128][128],temp[128];

    char line[128]; /* or other suitable maximum line size */

    for(i=0; i<128; i++)
        for(j=0; j<128; j++)
            arra[i][j] = '\0';

    for(i=0; i<128; i++)
        line[i] = '\0';

    if ( file != NULL )
    {
        i=0;

        while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
        {
            strcpy(arra[i], line);
            printf("%s ", arra[i]);
            i++;
        }

      //   for(i=0; i<128; i++)
      //   {
      //      for(j=0; j<128; j++)
      //      {
      //         if(strcmp(arra[i],arra[j])>=0)
      //         {
      //            temp=arra[j];
      //            arra[j]=arra[i];
      //            arra[i]=temp;
      //  }
      //  }
      // }
      // printf("%s ", arra[j]);

      fclose ( file );
    }
    else
    {
        perror ( "college.text" ); /* why didn't the file open? */
    }

    return 0;
}

1 个答案:

答案 0 :(得分:0)

从第二个循环更改 for(j = 0; j <128; j ++)至
for(j = i + 0; j <128; j ++)并尝试。