gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:05:19 25 4
gpt4 key购买 nike

您好,我一直在尝试开发一个项目,从输入文件中读取成绩,并根据包含总分的第一行将相同的成绩和平均值输出到另一个文件,但我完全迷路了。我尝试使用 getline() 函数读取显示为的成绩行姓名 7 8 9 10然后使用 istringstream 读取每个值。我似乎无法正确理解语法,我的代码只会获取每隔一行的成绩,并且字符串输出全为零....

这是我试图在乐谱中阅读并至少将它们作为整数单独打印出来的一种变体

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 更改为 ofstream 输出。使用 ofstream 就像使用 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 感到困惑,我会使用 istringstream 来读取每个数字并使用另一个类似的函数计算平均值。这是我的 istringstream 函数,用于计算平均值,假设最后读取的是总数。另一种方法是,因为总数已经给了你,我会把该行的所有输入存储在一个 vector 或数组中,然后得到最后一个元素除以大小 - 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;
}

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

关于c++ - 从文件中读取成绩并将平均值输出到另一个文件 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58826767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com