明解C语言,练习13-3,从文件中读入个人信息,按身高排序后显示

#include

#define NUMBER 6
#define F_PATH "D:\\C_C++\\ec13-3\\hw.dat"
typedef struct {
    char name[20];
    int height;
    float weight;
} student;
void swap(student *x,student *y)
{
    student tmp = *x;
    *x = *y;
    *y = tmp;
}
void sort(student data[],int n)
{
    int k = n - 1;
    while( k >= 0) {
        int i,j;
        for(i = 1,j = -1;i <= k;i++)
            if(data[i-1].height > data[i].height){
                j = i -1;
                swap(&data[i],&data[j]);
            }
        k = j;
    }
}
int main(void)
{
    FILE *fp;
    student str[10];
    if ((fp = fopen(F_PATH,"r")) == NULL)
        printf("\aIt is error!\n");
    else {
        for(int i=0;i < NUMBER;i++)
        {
            fscanf(fp,"%s%d%f",str[i].name,&str[i].height,&str[i].weight);
//            while((fscanf(fp,"%s%d%f",str[i].name,&str[i].height,&str[i].weight))==3);
        }
        sort(str,NUMBER);
        puts("-----------------------------------");
        for(int i=0;i < NUMBER;i++) {
            printf("%-8s %6d %6.1f\n",str[i].name,str[i].height,str[i].weight);
        }
        puts("-----------------------------------");
        fclose(fp);
    }
    return (0);
}

你可能感兴趣的:(明解C语言,练习13-3,从文件中读入个人信息,按身高排序后显示)