segmentation fault with fstream

I'm trying to read data in from a txt file using fstream. It works fine (complies and runs with the expected restul) if the code is in one cpp file. Unfortunately the project requirements say I have to use classes. So I make a stats class and the constructor for the Stats object is suppose to read in the data. So I'm thinking that I'm missing something in the translation from 1 file into breaking it up into three files, but I can't for the life of me figure out what it is. :(

Here is the code in my main file:
1
2
3
4
5
6
7
8
9
10
11
#include<iostream>
#include"Stats.h"

using namespace std;

int main(){

Stats myRain;

return 0;
}


here is the code from the Stats.cpp file with the relevant constructor function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>
#include"Stats.h"
#include<fstream>



Stats::Stats()
{
	numElements=25;
	ifstream inputFile;
	inputFile.open("data.txt");

		if (!inputFile)
		cout << "Error opening data file\n";
		else
		{ 
		for (int i= 0; i < numElements-1; i++)
		inputFile >> data[i];
		}

	inputFile.close();
}
Last edited on
Post the header too.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>

using namespace std;

class Stats
{
	private:
	int numElements;	
	double data[];
	

	public:
	Stats();
	int getNum();
	double getTotal();
	double getAvg();
	double getLargest();
	double getSmallest();
};


it works fine when its all in one file. So it seems like it must have something to do with the way I'm breaking it into seperate files.
Last edited on
double data[]; that's not right. I don't know what the standard says about this nor how compilers deal with it (I have a feeling it might be equivalent to double*). Anyway, it should be either double data[25]; or double* data; and then in Stats constructor, data = new double[numElements]; (and then delete[] data; in the destructor).
Last edited on
Topic archived. No new replies allowed.