How do I read in an enum value from a file?

Posted on 2007-08-11
Last Modified: 2010-04-01
Hi Experts,

In my VS native c++ console program, I define an enum e.g. Color {RED, GREEN, BLUE}.  This is logged to an ofstream such as:

ofstream my_ofs("blah");
Color my_color = RED;
my_ofs << my_color;

No problem.  Later I need to read in this value. I'd like to do something like this:

Color your_color;
ifstream my_ifs("blah");
my_ifs >> your_color;

This does not work because the compiler doesn't know how to read in a Color type.  But it's just an int in actuality, so it seems that something like this _should_ work. Any suggestions on the correct way to do this?

I don't care too much if the file actually stores the text "RED" or the integer code for it. However, the former would be preferred (though, that way probably entails much more code).

Question by:highqllc
    LVL 3

    Accepted Solution

    can you read int

    int a;
    your_color = (Color)a;

    Author Comment

    Right!  I suspected there was a simple way.  Thanks.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
      Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
    The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
    The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

    760 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    8 Experts available now in Live!

    Get 1:1 Help Now