How to read...?

T

Tommy

Hello everyone,
any idea how to read data from file into structure?
I have problem only with enum type.

Lets say I have enum type defined like this:

enum transport
{
bus,
plane
} ;

I have also structure

struct data
{
int number ;
transport tr ;
}

and I also have a binary file called data.dat which
looks more less like this:

1 bus
2 plane

And in main() i have

{
ifstream in("data.dat", ios::binary) ;
data buffer ;

// read number
in >> buffer.number ; // ok works well
// problem starts with enum
in >> buffer.tr ; // any idea how to read this?
}

Do I have to overload operator>> ?

Best regards
tommy
 
D

Dietmar Kuehl

Tommy said:
Do I have to overload operator>> ?

Yes. Well, you can do it differently but then you would need
a special approach to reading your enums.
 
T

Tommy

Yes. Well, you can do it differently but then you would need
a special approach to reading your enums.

OK, but here is another problem.
Back to my code:

ifstream in("data.dat", ios::binary) ;
data buffer ;

// read number
in >> buffer.number ; // ok works well
// problem starts with enum
in >> buffer.tr ; // any idea how to read this?

I was trying to overload operator>> like this:

ifstream& operator>>(ifstream &get_enum, transport &my_transport)
{
get_enum >> my_transport ;
return get_enum ;
}

but I got an error: warning C4717: 'operator>>' : recursive on all control
paths, function will cause runtime stack overflow
Any suggestions how to overload it correctly ? Any help will be really
appreciate

Regards
tommy
 
D

Dietmar Kuehl

Tommy said:
ifstream& operator>>(ifstream &get_enum, transport &my_transport)

Why do you want to restrict this operation to 'ifstream's? The same
logic should also work for 'std::istream'.
{
get_enum >> my_transport ;
return get_enum ;
}

This function obviously just calls itself! You need to impleemnt the
logic how to convert your value strings to the corresponding integer
in this function. Most likely, you read a string and compare it to
a collection of appropriate values, for example:

enum fb { foo, bar, foobar };
std::string const values[] = { "foo", "bar", "foobar" };
template <typename T, int sz> T* begin(T(&a)[sz]) { return a; }
template <typename T, int sz> T* end(T(&a)[sz]) { return a + sz; }

std::istream& operator>> (std::istream& in, fb& val) {
std::string tmp;
if (in >> tmp)
{
std::string const* it = std::find(begin(values), end(values));
if (it == end(values))
in.setstate(std::ios_base::failbit);
else
val = it - begin(values);
}
return in;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,201
Messages
2,571,052
Members
47,656
Latest member
rickwatson

Latest Threads

Top