reading a text file and returning enum

B

Ben

Hi all,

enum Colors defined as:
enum Colors{Red, Blue, Green};

I have a text file "colors.txt" with the following content, one per
line:
Red
Blue
Green.

My read() function is supposed to read an enumerated variable from
"colors.txt" file and to return a variable of type Colors. I'm not
sure how to do it.

My effort:

Colors read (ifstream inFile) {
char buffer[256];
while (!inFile.eof()) { //perhaps i don't even need this while
loop???
inFile.getline (buffer,100);
}
return (Colors(buffer)); // IT'S WRONG HERE!! ANY SUGGESTIONS??
}

Can anyone please show me the way..

Thanx for your time!
Ben
 
V

Victor Bazarov

Ben said:
enum Colors defined as:
enum Colors{Red, Blue, Green};

I have a text file "colors.txt" with the following content, one per
line:
Red
Blue
Green.

My read() function is supposed to read an enumerated variable from
"colors.txt" file and to return a variable of type Colors. I'm not
sure how to do it.

If the file contains three of them, one per line, how can the function
return only _one_ value?
My effort:

Colors read (ifstream inFile) {
char buffer[256];
while (!inFile.eof()) { //perhaps i don't even need this while
loop???
inFile.getline (buffer,100);
}
return (Colors(buffer)); // IT'S WRONG HERE!! ANY SUGGESTIONS??
}

Can anyone please show me the way..

If you need to convert a string into an enumerator, you have to write
the conversion yourself, there is no standard conversion defined for
'string -> enum' or vice versa.

Colors string2color(const std::string & s)
{
static std::pair<const char*, Colors> pairs[] =
{ { "Red", Red }, { "Blue", Blue }, { "Green", Green } };
for (int i = 0; i < sizeof pairs/sizeof pairs[0]; ++i)
{
if (s == pairs.first)
return pairs.second;
}
return Colors(777); // or any other value that doesn't represent
// a known color
}

Victor
 

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

No members online now.

Forum statistics

Threads
474,169
Messages
2,570,920
Members
47,462
Latest member
ChanaLipsc

Latest Threads

Top