我正在编程,要求我准备两个单独的输入文件,名称为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 ++文件,我不知道如何!我需要有一份软拷贝,我知道它是否能在那里找到我的文件!
答案 0 :(得分:0)
指定文件名的方式为“group1.txt”,只有程序在编译程序的当前工作目录中才能找到该文件。
有两种方法可以解决这个问题: