#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
// Here's the macro trick ----------------------------------------------------
// First, define your list
#define FRUITS(F) \
F(Apple), \
F(Pear), \
F(Banana), \
F(Strawberry)
// Create the Enums
#define F(e) e
enum Fruit { FRUITS(F), NumFruits };
#undef F
// Create the strings
#define F(s) #s
std::string FruitNames[] = { FRUITS(F) };
#undef F
// Here are a couple of conversion functions ----------------------------------
// just like Gamer2015 suggested
std::string totitle( std::string s )
{
for (char& c : s) c = std::tolower( c );
for (char& c : s) { c = std::toupper( c ); break; }
return s;
}
Fruit name_to_fruit( std::string s )
{
return Fruit( std::find( FruitNames, FruitNames + NumFruits, totitle( s ) ) - FruitNames );
}
std::string fruit_to_name( Fruit fruit )
{
return (fruit < NumFruits) ? FruitNames[ fruit ] : "";
}
// Let's have some fun --------------------------------------------------------
int main()
{
std::string users_fruit;
std::cout << "What is the name of your favorite fruit? ";
std::getline( std::cin, users_fruit );
switch (name_to_fruit( users_fruit ))
{
case Apple:
std::cout << "Sorry, I don't much care for an Apple.\n";
break;
case Strawberry:
std::cout << "Me too! I love Strawberries!\n";
std::cout << "(Especially with cereals like Golden Grahams.)\n";
break;
case NumFruits:
std::cout << "I've never heard of a \"" << users_fruit << "\".\n";
break;
default:
std::cout << "Yeah, " << fruit_to_name(name_to_fruit(users_fruit)) << "s are okay.\n";
break;
}
}
You might want to add some other validations to the user's input as well, such as trimming it, etc.
(I used Title Case. You can stick with ALL CAPS if you wish, just adjust line 37 to use a function that adjusts the string s appropriately.)