Dereferencing (?) error in code

Hello there. So this is an assignment for my physics course at uni wherein you have to write a piece of code that can read 50 floating point numbers from a .dat file and use these to calculate the mean, standard deviation and standard error of electronic charge.

The main thing here is the way in which they want you to write the code. You have to use the new function and read the data into a dynamic array (based on the number of specified data points, 50 in this case) without using vectors. The problem I think I have here is that the value pointed to by the *thedata pointer seems to be just the final value of the file, rather than an array of all of the values. I don't understand why It doesn't store it as an array of all the values. Any help on this would be greatly appreciated. Thanks.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
int N;
	cout << "How many data points are in the file?";
	cin >> N;



	// Ask user to enter filename
	string filename;
	cout << "Enter the file name\n";
	cin >> filename;

	// Open file and check if successful
	ifstream myfile(filename);

	if (!myfile.good()) {

		cerr << "Error. file could not be opened. Program will now terminate."<<endl;

		return(1);


	}


	// Allocate memory for data about to be read

	double *thedata = new double[N];

	
	
	// Read data from file, ignoring any additional bad data


	while (!myfile.eof()) {

		myfile >> *thedata;

		if (myfile.fail()) {

			myfile.clear();
			myfile.ignore();

		}
	}


	// Print data as a check

	//ONLY PRINTING FINAL VALUE
	cout << *thedata;
You are correct, and that's actually what is written.

"*thedata" is read, colloquially, as "what's stored at thedata". Now, if the name had been "a", still allocated as it is, what's stored at "a" is the first entry in the array.

There's nothing to loop through the array.

There are several ways to proceed, but one way is this:

1
2
3
4
5
int pos=0;

......

myfile >> thedata[ pos++ ];
Thanks so much man, it found the mean correctly after using what you said in a for loop.
Topic archived. No new replies allowed.