file io and enumerations

C

cpisz

How can I read and write an enum value to a file?

The code in question:

Cell temp;
temp.m_x = x;
temp.m_y = y;
file >> temp.m_type;

The error:
c:\Documents and Settings\christopher.pisz\My Documents\Visual Studio
Projects\parser\maze.cpp(108): error C2679: binary '>>' : no operator
found which takes a right-hand operand of type 'Cell::CELLTYPE' (or
there is no acceptable conversion)

The Cell defination:

class Cell
{
public:
enum CELLTYPE{ START, PASSABLE, IMPASSABLE, END, UNKNOWN};

Cell();
~Cell();

void Display();

int m_x,
m_y;
CELLTYPE m_type;
};

file is of course an ifstream declared and opened earlier...

At first I wanted to have the enumerated names in the input file so
that it would be reader friendly, then I tryed just using the number
values after I gave up on converting strings to enumerated values using
a long google search and not liking the ideas presented. Now I can't
even seem to read in numbers to an enumerated type. enum is seeming
less and less friendly. I thought the whole idea of enum was to make
things friendly to the coder and reader...

What is your ideas on a solution to this problem? Besides the obvious
of not using enum at all, but I don't like that, because m_type is not
an int, it is a cell type.

Is there an effiicient way to read in strings from the file such as
START, PASSABLE, etc. and convert them to an enumerated type?

If not, is there a way to just read in a number such as 0 and convert
it to the enumerated type START without using a switch statement and
having to edit it every time a new type is introduced?
 
I

Ian Collins

How can I read and write an enum value to a file?
You can just write it and provide a wrapper operator to read it:

#include <string>
#include <iostream>

enum E { A, B };

std::istream& operator>>( std::istream& in, E& e )
{
unsigned tmp;

in >> tmp;

e = static_cast<E>(tmp);

return in;
}

int main()
{
E e = A;

std::cin >> e;
}
 

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

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top