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 (i.e., 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++)?
1 Answer