Hi everyone!

I know there have been quite a few threads on this topic but I'm having a lot of trouble with one piece of code.

Basically, I have an input file with three columns and 500+ rows. I want to find the average of each column, and then subtract this average from each individual element in the colulmn.

i.e. x1 - avgx y1 - avgy z1 - avgz

My code is:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(){
	string data_array[3][2]; //You can make it dynamic to handle as much as the file has
        int i, sumx=0.0;
        float myFloat;
	float avg=0;
	ifstream in_file("data.txt");
	//Check if the file is open
		cout << "File not opened..." << endl;
		return 1;
	//read the file (two columns) to the array
	for(i=0; !in_file.eof(); i++){
		in_file >> data_array[i][0];
		in_file >> data_array[i][1];
	//Display the array
	for(i=0; i<3; i++){
               sscanf(data_array[i][0].c_str(), "%f", &myFloat);
	sumx +=myFloat;
	avg = (float)sumx/3;
        printf("The average is === %f\n", avg);
	return 0;


This is only a test file for a three row, 2 column file. It is working, however it's doing the sum after each column element and I get three output statements:

The average is === 0.333333
The average is === 1.333333
The average is === 3.000000

I only want to use the final value in my following calculations, any idea how I could?

Thanks :)

Reformat your code towards the bottom and the answer will be readily apparent.


Yes I solved the problem. I have now computed everything, the values print to stdout fine.

However, I'd like to get the output to save in a file, and using ofstream output("blah.txt") is not working..

Figured it out- sorry!

keep doing this :P