C语言文件操作,北林复试

#define _CRT_SECURE_NO_WARNINGS

#include<iostream>
using namespace std;
/*
Copyright Tracy Xiao
*/
struct student
{
	char num[20];//学号
	char name[20];//学生姓名
	float score1;//成绩
	float score2;//上机成绩
	float score;//总成绩
};

void main()
{
	FILE *fp = fopen("c:\\student.txt", "r");
	char c;
	int n = 0;//学生个数,即行数-1
	while (1)
	{
		c = fgetc(fp);
		if (c == '\n') n++;
		if (c == EOF) break;
	}

	freopen("c:\\student.txt", "r", fp);//重新打开文件

	struct student *stu = new student[n];//堆中开辟n个student对象

	while (1)
	{
		c = fgetc(fp);
		if (c == '\n') break;	//不读第一行
	}


	for (int i = 0; i < n;i++)//读取数据
	{
		fscanf(fp, "%s       %s          %f        %f", stu[i].num, stu[i].name, &stu[i].score1, &stu[i].score2);
		stu[i].score = stu[i].score1 + stu[i].score2;
	}

	fclose(fp);//关闭文件

	for (int i = 0; i < n - 1; i++)
	{
		for (int j = 0; j < n - 1 - i; j++)
		{
			if (stu[j].score>stu[j + 1].score)//按总成绩从小到大排序
			{
				student tmp = stu[j];
				stu[j] = stu[j + 1];
				stu[j + 1] = tmp;
			}
		}
	}

	//test:排序之后
	cout << "排序之后:" << endl;
	for (int i = 0; i < n; i++)
	{
		printf("%s       %s          %f        %f        %f\n",
			stu[i].num, stu[i].name, stu[i].score1, stu[i].score2, stu[i].score);
	}

	char s_name[20];
	cout << "请输入要查询的学生姓名:";
	scanf("%s", s_name);

	int flg = 0;//标记是否查到

	for (int i = 0; i < n; i++)//查找学生信息
	{
		if (strcmp(stu[i].name,s_name) == 0)//匹配字符串
		{
			flg = 1;
			cout << "学号:" << stu[i].num << endl;
			cout << "总成绩:" << stu[i].score << endl;
			break;
		}
	}
	if (flg == 0)
	{
		cout << "没有查到学生信息!" << endl;
	}
	/*
		写入student-sort.txt
	*/
	fp = fopen("c:\\student-sort.txt", "a");
	fprintf(fp, "%s", "学号        学生姓名    面试成绩    上机成绩");
	fprintf(fp,"\n");

	for (int i = 0; i < n; i++)
	{
		fprintf(fp, "%s       %s          %f        %f", stu[i].num, stu[i].name, stu[i].score1, stu[i].score2);
		fprintf(fp, "\n");
	}
	fclose(fp);

	system("pause");
}

TEST:

学号        学生姓名    面试成绩    上机成绩
2014153001       杨阳          58.5        78.2
2014153004       杨一          48.5        28.2
2014153055       杨二          65.5        38.2
2014153008       杨三          34.5        18.2  
2014153005       薛林          98.5        48.2   
2014153045      王诗萌          23.3        78.2    
2014153043      哈哈大          52.5        48.2     
2014153032      杨5          44.4        68.2      
2014153012      杨6          28.5        45.2
2014153032      杨7          23.5        23.2
2014153041      杨66          43.5        68.2

猜你喜欢

转载自blog.csdn.net/pastthewind/article/details/79563055