For the past while, I have gotten comfortable doing things a particular way when it comes to inputting data:
i) create text file whose first entry is N, an integer indicating the number of data entries following, and the actual data entries. For example, for 101 data values, the text file might look as follows:
101
0.276706347633276
0.486631466856855
0.63439588641705
0.740012950708629
. . .
ii) In C++, open the file, read the first entry, and use this number to create a dynamic array of this size, and fill the array:
e.g. -
. . .
vector<double> raw_Array;
ifstream in("Fourier_Forward_Data.txt", ios::in);
in >> N; //Input the vector dimension from the file
// Beginning of try block, for dynamic vector and array allocation
try {
// Resize raw_Array to accommodate the N data values
raw_Array.resize(N);
} // End of try block
catch (bad_alloc& xa) { // Catch block, for exceptions
in.close();
out.close();
cerr << "In catch block, so an exception occurred: " << xa.what() << "\n";
cout << "\nEnter any key to continue. \n";
cin >> rflag;
return 0;
} // End of catch block
for (int i = 0; i < N; i++){ //Input the raw_Array elements from the text file
in >> raw_Array[i];
}//End for i
. . .
However, I am starting a brand-new program and would like to try something a little different: I would like to avoid the need for the first entry in the input text file (the integer stating the number of data entries are to be input.) So the modified input file would be as follows
0.276706347633276
0.486631466856855
0.63439588641705
0.740012950708629
. . .
Note that the first value (101) is now not included.
The input data file could include a random number of entries (e,g. - 101, 1037, 10967, etc.). Whatever the number, I would like the C++ program to determine that number on its own, size the vector appropriately, and input the data as usual.
I am rusty when it comes to file manipulation, but I think the above code snippet would be modified as follows:
vector<double> raw_Array;
int N = 0; //The number of data entries which will be input from the file
ifstream in("Fourier_Forward_Data.txt", ios::in);
// Beginning of try block, for dynamic vector and array allocation
try {
while(!in.eof()){
N++;
// Resize raw_Array to accommodate the next data value
raw_Array.resize(N);
in >> raw_Array[N-1];
} // End while(!in.eof())
} // End of try block
catch (bad_alloc& xa) { // Catch block, for exceptions
in.close();
out.close();
cerr << "In catch block, so an exception occurred: " << xa.what() << "\n";
cout << "\nEnter any key to continue. \n";
cin >> rflag;
return 0;
} // End of catch block
. . .
Several questions:
Will this work?
The while(!in.eof()) loop is within the try-block. Is this okay? Or should the try-block be within the while loop? Does it matter?
Either way, the array is resized each time through the loop. Is there a better way to do this?
What is the "best practices" way of accomplishing this task?
Any advice and suggestions are appreciated.