Monday, April 28, 2008

Average a bunch of lines (C++)

A Short C++ program to average a bunch of entries on a bunch of lines. I.e.:




1 2 3 4 5 6 END OF LINE

7 8 9 10 11 12 END OF LINE

13 14 15 16 17 18 END OF LINE



Would average 1 7 13. 2 8 and 14 etc...

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>

using namespace std;

int main(int argc,char **argv) {

ifstream infile(argv[1]);

int count=0;
vector<double> sums(1000,0);
for(;!infile.eof();) {
string instring;
getline(infile,instring);

stringstream ss(instring);

for(int n=0;!ss.eof();n++) {
double cur;
ss >> cur;
sums[n]+= cur;
}
count++;
}

for(vector<double>::iterator i = sums.begin();i != sums.end();i++) {
cout << (*i)/count << " ";
}
cout << endl;

}

No comments: