我试图从.txt文件中读取一行中的逗号分隔数据,然后将数据解析为2个不同的数组(名称和indScores)。从indScores []中,我获得了特定名称的总体平均值,并将其存储到我的avg_scores []中。然后在最后,返回读取的总行数。
示例输入数据如下所示:
name1,x1,x2,x3,x4,x5
name2,y1,y2,y3,y4,y5
name3,z1,z2,z3,z4,z5
name4,a1,a2,a3,a4,a5
....
我的数组输出此
names[name2, name4, name6, name8,...]
avg_scores[x_avg, x_avg + y_avg, x_avg + y_avg + z_avg,...]
我的整体行数是我期待的一半。我是在错误的位置编制索引还是我的逻辑错误?
int ReadScores(string fileName, string names[], float avg_scores[], int array_size){
float indScores[array_size];
int lineCounter = 0;
string myLine, nameSubString, scoreSubString;
float scoreConvert = 0.0;
float averageScores = 0.0;
ifstream myFileIn;
//open the file
myFileIn.open(fileName, ios::in);
if (myFileIn.fail()){
cout << "Error opening "<< fileName << endl;
return 0;
}
int index = 0;
//read the file with a while loop until the end of file is reached
while (getline(myFileIn, myLine)){
averageScores;
getline(myFileIn, myLine);
//firstComma will hold the integer value of the index position of the first comma found
int firstComma = myLine.find(',');
//this should grab the the names at the beginning of each string on each new line
nameSubString = myLine.substr(0, firstComma);
names[index] = nameSubString;
int startingPos = 0;
float commaCounter = 0;
//find how many commas are in a string and use that to limit your loop
for (int ind = 0; ind < myLine.length(); ind++){
if (myLine[ind] == ',')
commaCounter++;
}
for (int ind = 0; ind < commaCounter; ind++){
//grab the first number and store it the scoreSubString variable
//this tells the myLine.substr to start after the very first comma
int found = myLine.find(',', firstComma) + 1;
scoreSubString = myLine.substr(found, myLine.find(','));
//change the value of firstComma to the next index location
firstComma = found + 1;
///convert string to number
stringstream(scoreSubString) >> scoreConvert;
///store number in float array
indScores[ind] = scoreConvert;
}
for (int ind = 0; ind < commaCounter; ind++){
averageScores = indScores[ind] + averageScores;
}
float averageOverall = averageScores/commaCounter;
//store the averageOverall into the avg_scores []
avg_scores[index] = averageOverall;
index++;
lineCounter++;
}
myFileIn.close();
return lineCounter;
}
答案 0 :(得分:0)
是的,一旦我删除了第二个getline(myFilenIn, myLine)
事情就开始匹配了。
我还需要在获取averageScores = 0
的{{1}}循环之前重置for
,并为averageScores
添加起始位置found
,我从一开始就不断开始。
我的新代码如下:
.find(',', found)
return lineCounter; }