2 回答

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個(gè)贊
/*
假如要讀取文件chengji.txt中的數(shù)據(jù)。
文件中數(shù)據(jù)如下:
學(xué)生編號(hào) 數(shù)學(xué) 英語
1 80 90
2 66 67
怎樣求各學(xué)生的平均成績和總的平均成績
*/
#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<<"學(xué)生編號(hào)\t平均成績"<<endl;
}
ofs<<num<<"\t"<<(math+english)/2<<endl;
sum_math+=math;
sum_english+=english;
count++;
}
if(count>0)
{
ofs<<endl;
ofs<<"數(shù)學(xué)平均成績:"<<sum_math/count<<endl;
ofs<<"英語平均成績:"<<sum_english/count<<endl;
}
ifs.close();
ofs.close();
return 0;
}

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
fscanf 函數(shù)可以從文件按照你的格式讀取文件數(shù)據(jù)
但是,請(qǐng)必須保證你的文件內(nèi)容和你所期望讀取的數(shù)據(jù)格式是一致的
如果你想從文件讀取一個(gè) float 和一個(gè) int,可以像這樣子:
float fvar = 0.0f; int ivar = 0; // 假設(shè) file 是一個(gè)有效的文件指針 ... fscanf ( file, "%f %d" , & fvar, & ivar ); |
- 2 回答
- 0 關(guān)注
- 111 瀏覽
添加回答
舉報(bào)