I looked at this in two different ways. In a language such as COBOL, the defining of a layout to match the line of data is very easy. In C++ too it is possible, using a data structure, to match the 13 and 7 character fields, repeated four times.
However, the resulting code ended up being longer and more complex than just using the ordinary C++ formatted input.
Example code the second way:
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 52
|
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
void getdata(istream & f, vector<double> &);
int main()
{
char filename[] = "fortran_data.txt";
ifstream fin(filename);
if (!fin.good())
{
cout << "File not open: " << filename << endl;
return 0;
}
vector<double> numbers;
getdata(fin, numbers);
for (int i=0; i<numbers.size(); ++i)
{
cout << i << " " << numbers[i] << endl;
}
return 0;
}
void getdata(istream & f, vector<double> & nums)
{
string line;
while (getline(f, line))
{
stringstream ss(line);
double n;
double dummy;
ss >> n >> dummy;
while (ss.good())
{
nums.push_back(n);
ss >> n >> dummy;
}
}
}
|
output (abbreviated):
0 0
1 8.43491e-05
2 0.00029467
3 0.000490358
...
84 0.00674385
85 0.0102937
86 0.00693213
87 0.00472209 |
The function call at line 24 reads the data into a vector of doubles.
At line 38, a whole line is read, and then a stringstream (extremely useful tool) is made from the line.
Line 45 (and 49), the required value
n and unwanted value
dummy are extracted.
Line 48, the wanted value is stored.
Finally, at lines 26 to 29 the contents of the vector are displayed.