Issue
I have to make a program that read from a file .dat that have two columns but i'm interest just to one. Every columun contains a lot of values, stored each ones in line. I want to gather them in groups (arrays) of 120 elements and then calculate the avarage value, proceeding like this until the EOF. Once calculated the avarage i save it in an external file. The code that i wrote is like this:
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
#include<cmath>
using namespace std;
int i, k=1;
double temp [120];
double tmean, total=0;
int main()
{
ifstream fin ("Data_Acquisition(1).dat");
if (!fin)
{
cerr << "\nError: the file can't be open.\n" << endl;
exit(1);
}
string line;
ofstream fout;
fout.open("tmean.dat", ios::out);
fout << "Tmean" << endl;
for(i=0; i<=120; i++)
{
getline(fin,line);
istringstream ss(line);
double col1;
double col2;
ss >> col1;
ss >> col2;
temp[i] = col2;
total += temp[i];
k++;
}
tmean = total/k;
fout << tmean << endl;
}
My question is: once calculated the avarage of the first group of values, how can i say to the program to continue with others until the file ends?
Solution
You currently have an inner loop...
...
for(i=0; i<=120; i++)
{
...
}
tmean = total/k;
fout << tmean << endl;
...just wrap that in an outer for loop...
while (fin >> std::skipws && !fin.eof())
{
for(i=0; i<=120; i++)
{
...
}
tmean = total/k;
fout << tmean << endl;
}
You might want to fix the bugs too: k
starts at 1 and is incremented for each value read, so ends up being 1 more than it should me: start at 0; and Derek's already commented on another issue.
Answered By - Tony Delroy Answer Checked By - Marilyn (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.