I'm trying to write a function that is passed a pointer to a string * filename and a double[] data array. The function is supose to read in a set of double data from the text file and store it in the array.
The data in file is of format
1.3245
1.3456
..
.
The following is the function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
void ReadInFiles(string * filename, double[] * dataArray)
{
ifstream myFile;
double num;
myFile.open(*filename);
if(!myFile)
{
cerr << "Unable to open file datafile.txt";
exit(1); // call system to stop
}
int i = 0;
while(!myFile.eof)
{
num = myFile.get();
*dataArray[i] = num;
i++;
}
}
My questions are
1) I know I'm passing the parameters wrong. Can someone please tell me the correct way to write it?
2) Is the method for reading in double array correct? I'm using <fstream>
Personally if I HAD to return an array I would make it the return value because you don't know what size it is before you read in the data. So I would create the array inside the function.
1 2 3 4 5 6 7
#include <string>
double* ReadInFiles(const std::string& filename)
{
//... create array
//... read in values.. resizing array as required
}
Do you *have to* read the values into an array for the assignment? Or do you have a choice?
Because it would be much easier and better to read the values into a std::vector which is like an array but better and safer.
@Galik: Thanks. No I don't have to use arrays. In fact, after your suggestion, I'm trying to use vectors now.
However, my biggest concern is with reading in the data from file. The entries I have in the text file are stored as doubles. Should I read it in as a string first and then cast it to double or I can just directly store it into the vector<double>.
I tried using the following but it doesn't seem to work.
I literally spent more than 6 hours trying to figure out how to convert string to double. I tried using strtod but it didn't work.
The good thing is that the above works. However, the bad thing is, I still don't know how to convert a string to double. I tried all the examples from google search but it always had some error related to the 1st character.