gpt4 book ai didi

c++ - 正确使用嵌套循环和 fin

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

我有一个关于在 C++ 中正确使用 fin 和循环的问题。我有一个文件,我从中读取了 78 行数据,其中包括滑雪胜地名称、海拔高度,然后是 12 个数字,即每月降水量。该程序应该从该文件中读取,然后将名称、海拔和年平均降水量输出到另一个文件。出于某种原因,我无法让平均值正常工作。我必须为 78 行中的每一行运行一个循环,然后运行一个嵌套循环来处理 12 个月中的每一个月。

我还必须使用一个我不知道放在哪里的 cin.ignore。

代码:

int main() {

ifstream fin("../Debug/monthlyPrecipitation.txt");

if (fin.fail())
{
cout << "Error opening file." << endl;
}

ofstream fout;
fout.open("../Debug/annualPrecipitation.txt", ios::app);

int elevation;
const int MONTHSPERYEAR = 12;
double average, precipTotal, precip;
string stationName;

fout << "Annual Precipitation Report" << endl;
fout << endl;
fout << "Weather Station" << setw(18) << "Elevation" << setw(12) << "Precipitation" << endl << endl;

for (int counter = 1; counter <= 78; ++counter)
{
getline(fin, stationName, '\t');
fin >> elevation;

for (int counter = 1; counter <= 12; ++counter)
{
fin >> precip;
precipTotal = precipTotal + precip; //the issue is here
}

average = precipTotal / MONTHSPERYEAR;

fout << stationName << setw(22) << elevation << setw(12) << average << endl;
}

谢谢。

最佳答案

随着污染 precipTotal,您似乎忘记了将行转换为字符串流。我假设您文件中的一行如下所示:

Resort_Name 高程 precip1 precip2 ... precip12

如果你读到那一行,那么你就捕获了所有的原则,然后当你进入内循环时,你就在下一行阅读。您需要做的是获取该行,并将其转换为字符串流。然后,将度假村名称读入不同的字符串,将海拔读入一个 int,然后计算平均值而不影响总数。

关于c++ - 正确使用嵌套循环和 fin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36024109/

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