简体   繁体   中英

How to read a character or string and automatically convert to a number (C/C++)?

Suppose I am working on a card game, and I am using the numbers 0 to 3 to represent the suits internally, as it's easier to work with numbers. So:

0 is equivalent to hearts
1 is equivalent to clubs
2 is equivalent to spades
3 is equivalent to diamonds

When I need to output the suits as strings, though, I can easily use an array of strings to convert them, like this one:

char *suits[] = {"heats","clubs","spades","diamonds"};

So that I can type:

cout << suits[card.suit] 

and the output would be the exact string of the suit.

What if I want to do this the other way around though? That is, I'll be reading the suits from a file as strings, and I want to convert them to their respective numerical value (0 to 3) on the fly. How can I do it?

My initial idea was to create a very small hash table (ie, 4 elements in this case), then hash the strings as I read them and get their respective numerical value from the hash table.

Is there an easier way I am missing (specifically in C or C++)?

std::map<std::string, int> assoc;
assoc["hears"] = 0;
assoc["clubs"] = 1;
...

char *suits[] = {"heats","clubs","spades","diamonds"};

for (char *data : suits)
{
   std::cout << assoc[data];
}

Like Joachim said, I would recommend a std::map<std::string, int> .

You can then do stuff like.

std::cout << map["heart"];

I would recommend to check out the std::map class as it is quite a nice tool, but also holds some gotchas.

If you want to use it in both directions, you could also use a boost::bimap .

std::map<std::string, int id> cardsToIdMap;

int stringToCardId(std::string s) {
    return cardsToIdMap[s];

}

A map is hugely overkill here:

#define SIZE(x) (sizeof (x)/sizeof(*(x)))
const char *suits[] = {"heats","clubs","spades","diamonds"};

int suit_to_int(char *s)
{
    for(int x=0; x<SIZE(suits);x++)
         if(strcmp(s, suits[x])==0)
               return x;
    return SUIT_ERR;
}    
char* suit;
if (*suit == 'h') {
    return 0;
} else if ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM