Hello,
I've got a simple program intended to read in one column of float data from a .txt file (with a variable number of lines) into a dynamically allocated array. The array contents should then be written to the screen, to test if this was successful.
However, the code output is all gibberish (zeros or numbers like 5.60519e-045 and 1.62236e-007).
I'm pretty sure the problem is in dynamically allocating the array, since if I try using a static array for a known number of lines, the code works fine. However, since I'm running it for a large number of files with different numbers of lines I really want to get the dynamically allocated version to work.
The relevant code is provided below.
Thanks for any help you can provide.
/* This program should read in the name of a file,
* access the file, and read one column of float data
* (with a variable number of lines) into a
* dynamically allocated array. The array contents
* should then be written to the screen, as a check.
*/
#include<iostream>
#include<sstream>
#include<fstream>
int main()
{
using namespace std;
// Get filename from user and open file
//<snip>
// Determine number of lines in file
int nLines = 0;
while (!data.eof())
{
string line;
getline (data, line);
nLines++;
}
cout << "number of lines = " << nLines << endl;
// Declare dynamically allocated array
float* array = new float[nLines];
// Loop to extract data from file to array,
// and output to screen
for (int i = 0; i < nLines; i++)
{
data >> array[i];
cout << array[i] << endl;
}
data.close();
// Clean up array
delete[] array;
//end program
cin.clear();
cin.ignore(255, '\\n');
cin.get();
return 0;
}