I wish if somebody could help me in reading a file part by part.
I am enclosing a sample file below. Actually my file contains some 7000 lines and each part is separated by a comment line. I wanted to know how to process each segment separately but add the calculation obtained from each segment into one.
For example,
Input file:
!Comment
U 2.0 4.5 4.0
O 3.4 4.5 -1.9
U 5.6 4.5 2.9
Y 8.0 4.5 4.3
K -11.0 4.5 5.7
!Comment
I 6.0 4.5 7.9
U 2.8 4.5 -12.3
G 2.8 4.5 6.1
U -22.0 9.4 8.9
In the first segment between two comment line I wanted to calculate difference between column 2, 3 and 4 where first column is U. Similarly in next segment. The difference obtained from each segment has to be added for further calculation.
Are you interested only in lines where the first column is 'U' ?
Are the other lines to be ignored, or also processed in some way.
Is it important to keep each block of lines separated?
It isn't clear exactly what calculation you want to do with columns 2, 3 and 4.
An example would be useful. Which value or set of values do you want to derive from each block?
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
usingnamespace std;
int main()
{
ifstream fin("data.txt");
string line;
while (getline(fin, line) && line.size() )
{
if (line[0] == '!')
{
// Add end-of-block processing here
continue; // ignore comment line
}
istringstream ss(line);
char id;
double a, b, c;
if ( ss >> id >> a >> b >> c)
{
if (id == 'U') // process line type U
{
// do something with a, b and c
cout << setw(3) << id << setw(6) << a << setw(6) << b << setw(6) << c << '\n';
}
}
}
return 0;
}
Output:
U 2 4.5 4
U 5.6 4.5 2.9
U 2.8 4.5 -12.3
U -22 9.4 8.9