By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,194 Members | 859 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,194 IT Pros & Developers. It's quick & easy.

reading a text file and returning enum

P: n/a
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
Jul 22 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Ben wrote:
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[i].first)
return pairs[i].second;
}
return Colors(777); // or any other value that doesn't represent
// a known color
}

Victor
Jul 22 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.