2 回答

TA贡献1772条经验 获得超5个赞
/*
假如要读取文件chengji.txt中的数据。
文件中数据如下:
学生编号 数学 英语
1 80 90
2 66 67
怎样求各学生的平均成绩和总的平均成绩
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string line;
int head=0,count=0,num;
float math,english,sum_math=0,sum_english=0,average;
ifstream ifs("chengji.txt");
if(!ifs) return -1;
ofstream ofs("chengji_result.txt");
if(!ofs) return -2;
while(getline(ifs,line))
{
istringstream is(line);
if(head==0)
{
//跳过第一行的表头
head=1;
continue;
}
is>>num>>math>>english;
if(count==0)
{
ofs<<"学生编号\t平均成绩"<<endl;
}
ofs<<num<<"\t"<<(math+english)/2<<endl;
sum_math+=math;
sum_english+=english;
count++;
}
if(count>0)
{
ofs<<endl;
ofs<<"数学平均成绩:"<<sum_math/count<<endl;
ofs<<"英语平均成绩:"<<sum_english/count<<endl;
}
ifs.close();
ofs.close();
return 0;
}

TA贡献1802条经验 获得超5个赞
fscanf 函数可以从文件按照你的格式读取文件数据
但是,请必须保证你的文件内容和你所期望读取的数据格式是一致的
如果你想从文件读取一个 float 和一个 int,可以像这样子:
float fvar = 0.0f; int ivar = 0; // 假设 file 是一个有效的文件指针 ... fscanf ( file, "%f %d" , & fvar, & ivar ); |
- 2 回答
- 0 关注
- 115 浏览
添加回答
举报