从文件中读取成绩并将平均值输出到另一个文件C++



嗨,我一直在尝试一个项目,从输入文件中读取成绩,并将相同的成绩和基于第一行的平均值输出到另一个文件,其中包含总数,我完全迷失了方向。我试着使用getline((函数读取显示为姓名7 8 9 10然后使用distingstream读取每个值。我似乎无法正确处理语法,我的代码只会每隔一行获得一行等级,字符串输出的都是零。。。。

这是我试图在分数中读取的内容的一个变体,至少将它们单独打印为整数

while (getline(fin,grades))
{
getline(fin,grades);
std::cout << grades;
std::istringstream str(grades);
int score;
while (str>>score)
{
int s;
str >> s;
std::cout << score<< 'n';
}

非常感谢的帮助

根据您对输入文件的描述,我认为您所拥有的是正确的,只是在while循环之后您不需要再次使用getline,您似乎在第二个while循环中读取了两次score,int score可能应该改为double,并且您应该将couts改为流输出。使用流就像使用couts一样,它是这样的:

ofstream out(outputFile); // open the output file 
// for output average
out << grades << average(str) << "n"; // output your stuff to the file in the while loop like this 
out.close(); // closing the file 

既然你对istringstream感到困惑,我会用istringsream来读取每个数字,并使用另一个函数来计算平均值。这是我的distingstream函数,假设最后读取的是总数,来计算平均值。另一种方法是,既然总数已经给了你,我会把这条线的所有输入存储在一个向量或数组中,然后得到最后一个元素除以大小-1,这应该会给你平均值。

double average(istringstream& str){ // compute the average based on the line stream  
double sum = 0; // sum of all the numbers in a line 
int count = 0; // number of numbers in a line 
double score; // score that is being read in the line 
while(str>>score){ // can read a score
sum += score; // add the scores to a sum 
count++; // count the number of numbers in the line
}
sum = sum - score; // the last thing is the line is the total ? 
count = count - 1; // assuming the last thing in the line is the total ? 
return sum/count; 
}

希望这将提供足够的提示来做到这一点。哦,别忘了关闭输入流和输出流。谢谢

最新更新