标签归档:文件

将文件输入信息按身高排列

文件信息

将下列信息保持为hw.dat文件

Aiba 160 59.3
Kurata 162 51.6
Masaki 182 76.5
Tanaka 170 60.7
Tsuji 175 83.9
Washio 175 72.5

将该文件与下列c代码文件放在同一个文件目录内,编译下列c代码,生产可执行文件,执行文件排序显示

#include <stdio.h>

typedef struct gstudent {
	char 	name[128];
	double 	height;
	double 	weight;
} student;

int get_num(FILE *file);
void swap(student *pa, student *pb);
void bubble(student data[], int len);

int main(void)
{
	FILE *fp;

	fp = fopen("hw.dat", "r");
	double 	hsum = 0.0;
	double 	wsum = 0.0;
	int 	num = get_num(fp);
	student stu[num];
	
	if ((fp = fopen("hw.dat", "r")) == NULL) {
		puts("\afile open failed");
	} else {
		int i = 0;
		while (fscanf(fp, "%s%lf%lf", stu[i].name, 
			&stu[i].height, &stu[i].weight) == 3)
			i++;

		bubble(stu, num);

		for (i = 0; i < num; i++) {
			printf("%-10s %5.1f %5.1f\n", stu[i].name, 
				stu[i].height, stu[i].weight);	
			hsum += stu[i].height;
			wsum += stu[i].weight;
		}
		puts("---------------------------");
		printf("average    %5.1f %5.1f\n", hsum / num, wsum / num);
		fclose(fp);
	}

	return 0;
}

int get_num(FILE *fp)
{
	int cnt = 0;
	char name[128];
	double height, weight;
	while (fscanf(fp, "%s%lf%lf", name, &height, &weight) == 3)
		cnt++;

	return cnt;
}

void swap(student *pa, student *pb)
{
	student tmp = *pa;
	*pa = *pb;
	*pb = tmp;

	return;
}

void bubble(student data[], int len)
{
	while (len > 0) {
		int i;
		for (i = 0; i < len - 1; i++)
			if (data[i].height > data[i + 1].height)
				swap(&data[i], &data[i+1]);
		len = i;
	}

	return;
}

继续阅读