为了账号安全,请及时绑定邮箱和手机立即绑定

怎样只把int型数据读出? 只把int型数据读到一个int型的数组里

怎样只把int型数据读出? 只把int型数据读到一个int型的数组里

C++
青春有我 2023-03-05 09:05:39
1 2 3 43 4 5 61.22 2.22 3.33 4.11·
查看完整描述

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;
}

 


查看完整回答
反对 回复 2023-03-08
?
慕后森

TA贡献1802条经验 获得超5个赞

fscanf 函数可以从文件按照你的格式读取文件数据

但是,请必须保证你的文件内容和你所期望读取的数据格式是一致的

如果你想从文件读取一个 float 和一个 int,可以像这样子:


float fvar = 0.0f;int ivar = 0; // 假设 file 是一个有效的文件指针 ...fscanf( file, "%f %d", & fvar, & ivar );


查看完整回答
反对 回复 2023-03-08
  • 2 回答
  • 0 关注
  • 115 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号