我正在做一个程序,要求我准备两个单独的输入文件,名称为 group1.txt 和 group2.txt,然后创建一个程序来查找每个组的平均分数
我写了这个,但它找不到我的文件,因为我不知道一些帮助,也许谢谢!
这是代码:
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
string line;
const int num_lines = 10; //change numline to any number you like, its to set the size of the array
string sub_code[num_lines];
float avrgs[num_lines];
string sub_code2[num_lines];
float avrgs2[num_lines];
ifstream myfile ("group1.txt");
int sum=0,score=0,j=1,i=0,i2=0;
double ave=0.0;
if (myfile.is_open())
{
while ( myfile>>line )
{
//cout<<line<<endl;
sub_code[i] = line;
while ( myfile>>score && score <100 && score >= 0)
{
sum += score;
j++;
}
ave = sum/j;
j=1;
sum = 0;
avrgs[i]=ave;
i++;
}
}
else
{cout << "Unable to open file"<<endl;}
myfile.close();
//this is for the secode line
ifstream myfile2 ("group2.txt");
if (myfile2.is_open())
{
while ( myfile2>>line )
{
//cout<<line<<endl;
sub_code2[i2] = line; //add all the subject code into the array to store sub codes
while ( myfile2>>score && score <100 && score >= 0) //well basically the score should be between 0 - 100,
{ //so -999 wont be read. Can change to while ( myfile2>>score && score!=-999)
sum += score; //read each grade and add it to sum
j++; //just to know how many grades are there so that division can be done
}
ave = sum/j; //find the average.
j=1; //set j back to 1, cause j is used to count the number of marks.
sum = 0; //since its sum+=score, we need to set sum back to 0, or else it will be adding on to the old marks
avrgs2[i2]=ave; //add that calculated ave into the array for average
i2++; //i2 is to basically know how many entries are in the file for grp2
}
}
else
{cout << "Unable to open file"<<endl;}
myfile2.close();
int gr1,gr2;
//outputing the averages and so on...
for (gr1=0;gr1<i;gr1++)
{
for(gr2=0;gr2<i2;gr2++)
{
if(sub_code[gr1]==sub_code2[gr2]) // compare subject id before displaying
{
cout<<sub_code[gr1]<<"\t"<<" 1 "<<avrgs[gr1]<<endl;
cout<<sub_code2[gr2]<<"\t"<<" 2 "<<avrgs2[gr2]<<endl;
break;
}
}
}
//
cout<<endl;
double grpave1=0,grpave2=0;
//to find the average of each group
for (gr1=0;gr1<i;gr1++)
{
grpave1+=avrgs[gr1];
}
for(gr2=0;gr2<i2;gr2++)
{
grpave2+=avrgs2[gr2];
}
grpave1=grpave1/i;
grpave2=grpave2/i2;
cout<<"Average for group 1:"<<grpave1<<endl;
cout<<"Average for group 2:"<<grpave2<<endl;
system("pause");
return 0;
}
只需要知道如何获取我的文件!我已经使用 C++ 文件放入了桌面、我的文档、项目,但我不知道如何!另外,我需要一份软拷贝,我不知道它是否能够在其中找到我的文件!