C++读dat文件

编程实现简易的学生成绩管理系统。
(1)文件score.dat中存放了30名学生的序号和6次考试成绩,请从该文件中读取数据;
(2)计算每名学生的总分;
(3)输出总分最高和最低的学生序号及分数;

(4)根据输入的学生序号,输出该生各次考试成绩和平均成绩;

各要求比较简单,我只实现读数据部分,将结果存在结构体中,也可以存在vector中。

代码如下:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

struct Data       //注:也可以使用vector来存数据
{
	int A;
	int B;
	int C;
	int D;
	int E;
	int F;
};

int StringToInt(string str)
{
	int score = 0;
	int i = 0;
	while (str[i] != '\0')
	{
		score = score * 10 + str[i] - '0';
		i++;
	}
	return score;
}


int main()
{
	Data *student = new Data[30];
	//Data **student =new Data*[30];    //如果使用指针数组来,但是不能这样赋值:student[0]->A=1;
	string fileName = "score.dat";
	ifstream in;           //ifstream读文件(ofstream写文件)
	in.open(fileName);
	if (!in)
	{
		cout << "打开文件出错!" << endl;
		return 1;
	}
	int temp;
	int index = 0;
	while (in >> temp)
	{
		in >> temp;             //第一个序号不用
		student[index].A = temp;
		in >> temp;
		student[index].B = temp;
		in >> temp;
		student[index].C = temp;
		in >> temp;
		student[index].D = temp;
		in >> temp;
		student[index].E = temp;
		in >> temp;
		student[index].F = temp;
		index++;
	}
	for (int i = 0; i < 30; i++)
		cout << student[i].A<<'	'<<student[i].B<<'	'<<student[i].C<<'	'<<student[i].D<<'	'<<student[i].E<<'	'<<student[i].F<< endl;
	delete[] student;
	return 0;
}


结果测试:


  • 8
    点赞
  • 63
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值