Pe*******@gmail .com wrote:
[snip]
But it is not very straight forward to me how to read a file with both
kinds of records. Would you please help me?
Best wishes,
Peng
My preferred method is to roll everything up into a class or struct.
With your example, the result would look something like:
#include <iostream>
#include <string>
#include <sstream>
struct record
{
int w, h, t ;
// Put constructors and other members if you want them.
} ;
std::istream &operator>>(std ::istream &is, record &r)
{
int w, h, t ;
std::string s ;
if (std::getline(i s, s))
{
std::istringstr eam ss(s) ;
if (ss >> w >> h)
{
r.w = w ;
r.h = h ;
if (ss >> t)
r.t = t ;
else
r.t = 1 ;
}
}
return is ;
}
std::ostream &operator<<(std ::ostream &os, const record &r)
{
os << r.w << ' ' << r.h << ' ' << r.t ;
}
Now you can do all sorts of neat stuff. You could read the file like
you were original trying to:
record r ;
while (in_file >> r) { ... }
But you could also easily create a whole vector/list/etc from your file
in one command:
#include <vector>
#include <algorithm>
#include <iterator>
....
std::vector<rec ord> records ;
std::copy(std:: istream_iterato r<record>(in_fi le),
std::istream_it erator<record>( ),
std::back_inser ter(records)) ;
Or my favorite, you could create a function object to process a record,
and then process the whole file with one command:
class process_record
{
public :
void operator()(cons t record &r)
{
// Do some record processing.
std::cout << "I just processed record: "
<< r << std::endl ;
}
} ;
....
std::for_each(s td::istream_ite rator<record>(i n_file),
std::istream_it erator<record>( ),
process_record( )) ;
Anyhow, I hope this at least gives you some ideas of how to approach
your problem. Good luck!
-Alan