PengYu.UT@gmail.com wrote:
[snip][color=blue]
> 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
>[/color]
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(is, s))
{
std::istringstream 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<record> records ;
std::copy(std::istream_iterator<record>(in_file),
std::istream_iterator<record>(),
std::back_inserter(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()(const record &r)
{
// Do some record processing.
std::cout << "I just processed record: "
<< r << std::endl ;
}
} ;
....
std::for_each(std::istream_iterator<record>(in_fil e),
std::istream_iterator<record>(),
process_record()) ;
Anyhow, I hope this at least gives you some ideas of how to approach
your problem. Good luck!
-Alan