【发布时间】:2012-04-18 03:35:32
【问题描述】:
我有一个文本文件,其中包含每条记录的名称、年龄和 gpa。我写了一个函数 getgpa,它应该计算文件(整个类)的平均 gpa。问题是当我提取field1(姓名)、field2(年龄)和field3(gpa)时,我可以很容易地计算出全班的平均gpa。但是当我尝试只提取 field3 时,我没有任何结果。如何仅提取每条记录的 field3 (gpa)?我要提取的功能就在下面。我正在使用 Dev-C++。您的帮助将不胜感激。谢谢。
int student::getgpa()
{
double field3, gpa; double sumGPA=0; int count=0;
string field1; int field2;
char line[256];
cout<<"call of the function 'getgpa' " <<endl;
ifstream IS ("student.dat", ios::in);
while (!IS.eof())
{
if(IS>>field1>>field2>>field3) //where the problem is!
{
sumGPA=sumGPA+field3;
count++;
}
}
IS.close();
if (count>0) //just to make sur not to divide by zero!!
cout<<"gpa of the students:" <<sumGPA/count<<endl;
}
【问题讨论】:
-
if(IS>>field1>>field2>>field3) //where the problem is!你说提取所有 3 个字段都有效。问题出在哪里? -
我相信将
IS>>field1>>field2>>field3直接移动到while 循环中会比基于eof更好。见parashift.com/c++-faq-lite/input-output.html#faq-15.5 -
我试图只写 if(IS>>field3) 而不是 if(IS>>field1>>field2>>field3)。因为我只需要field3来计算班级的整体gpa。所以我不想提取所有三个字段,而只提取我计算所需的一个。但是当我这样做时它不起作用。
标签: c++ file field extract fstream