Coming Soon
This lesson is currently being developed
Converting an enumeration to and from a string
Learn about Converting an enumeration to and from a string in C++.
What to Expect
Comprehensive explanations with practical examples
Interactive coding exercises to practice concepts
Knowledge quiz to test your understanding
Step-by-step guidance for beginners
Development Status
Content is being carefully crafted to provide the best learning experience
Preview
Early Preview Content
This content is still being developed and may change before publication.
13.4 — Converting an enumeration to and from a string
In this lesson, you'll learn how to convert enumerations to human-readable strings and convert string values back to enumerations - essential skills for user interfaces and data processing.
The problem with enumeration output
As you've seen, when you print an enumeration directly, it shows the underlying integer value rather than a meaningful name:
#include <iostream>
enum Color
{
red,
green,
blue,
yellow
};
int main()
{
Color favoriteColor = blue;
std::cout << "My favorite color is: " << favoriteColor << std::endl;
return 0;
}
Output:
My favorite color is: 2
This output isn't very user-friendly. It would be much better to show "My favorite color is: blue" instead of a number.
Converting enumeration to string
There are several ways to convert an enumeration to a string. Let's start with the most straightforward approach using a function:
#include <iostream>
#include <string>
enum Color
{
red,
green,
blue,
yellow
};
std::string colorToString(Color color)
{
switch (color)
{
case red: return "red";
case green: return "green";
case blue: return "blue";
case yellow: return "yellow";
default: return "unknown";
}
}
int main()
{
Color favoriteColor = blue;
std::cout << "My favorite color is: " << colorToString(favoriteColor) << std::endl;
return 0;
}
Output:
My favorite color is: blue
More complex enumeration to string conversion
Here's a more practical example with a larger enumeration:
#include <iostream>
#include <string>
enum GameState
{
mainMenu,
characterSelection,
loading,
inGame,
paused,
gameOver,
settings
};
std::string gameStateToString(GameState state)
{
switch (state)
{
case mainMenu: return "Main Menu";
case characterSelection: return "Character Selection";
case loading: return "Loading";
case inGame: return "In Game";
case paused: return "Paused";
case gameOver: return "Game Over";
case settings: return "Settings";
default: return "Unknown State";
}
}
void displayGameState(GameState state)
{
std::cout << "Current game state: " << gameStateToString(state) << std::endl;
}
int main()
{
GameState currentState = inGame;
displayGameState(currentState);
currentState = paused;
displayGameState(currentState);
return 0;
}
Output:
Current game state: In Game
Current game state: Paused
Converting string to enumeration
Converting from string back to enumeration is more complex and requires parsing the string to find the matching enumerator:
#include <iostream>
#include <string>
enum Priority
{
low,
medium,
high,
critical
};
std::string priorityToString(Priority priority)
{
switch (priority)
{
case low: return "low";
case medium: return "medium";
case high: return "high";
case critical: return "critical";
default: return "unknown";
}
}
bool stringToPriority(const std::string& str, Priority& priority)
{
if (str == "low")
{
priority = low;
return true;
}
else if (str == "medium")
{
priority = medium;
return true;
}
else if (str == "high")
{
priority = high;
return true;
}
else if (str == "critical")
{
priority = critical;
return true;
}
return false; // Invalid string
}
int main()
{
Priority taskPriority;
std::string input = "high";
if (stringToPriority(input, taskPriority))
{
std::cout << "Successfully parsed priority: "
<< priorityToString(taskPriority) << std::endl;
}
else
{
std::cout << "Invalid priority string: " << input << std::endl;
}
return 0;
}
Output:
Successfully parsed priority: high
Using arrays for conversion (advanced technique)
For enumerations with consecutive values starting from 0, you can use arrays for efficient conversion:
#include <iostream>
#include <string>
enum Direction
{
north,
south,
east,
west,
directionCount // This will be 4, useful for array sizing
};
// Array of strings corresponding to enumeration values
const std::string directionNames[directionCount] =
{
"north", // direction[0] corresponds to north
"south", // direction[1] corresponds to south
"east", // direction[2] corresponds to east
"west" // direction[3] corresponds to west
};
std::string directionToString(Direction dir)
{
if (dir >= 0 && dir < directionCount)
{
return directionNames[dir];
}
return "invalid";
}
bool stringToDirection(const std::string& str, Direction& dir)
{
for (int i = 0; i < directionCount; ++i)
{
if (directionNames[i] == str)
{
dir = static_cast<Direction>(i);
return true;
}
}
return false;
}
int main()
{
Direction playerDirection = east;
std::cout << "Player is facing: " << directionToString(playerDirection) << std::endl;
// Convert string to direction
std::string input = "north";
Direction newDirection;
if (stringToDirection(input, newDirection))
{
std::cout << "Changed direction to: " << directionToString(newDirection) << std::endl;
}
else
{
std::cout << "Invalid direction: " << input << std::endl;
}
return 0;
}
Output:
Player is facing: east
Changed direction to: north
Handling user input with enumerations
A practical example of using string conversion for menu systems:
#include <iostream>
#include <string>
enum MenuOption
{
newGame,
loadGame,
settings,
quit
};
std::string menuOptionToString(MenuOption option)
{
switch (option)
{
case newGame: return "new";
case loadGame: return "load";
case settings: return "settings";
case quit: return "quit";
default: return "unknown";
}
}
bool stringToMenuOption(const std::string& str, MenuOption& option)
{
if (str == "new" || str == "n")
{
option = newGame;
return true;
}
else if (str == "load" || str == "l")
{
option = loadGame;
return true;
}
else if (str == "settings" || str == "s")
{
option = settings;
return true;
}
else if (str == "quit" || str == "q")
{
option = quit;
return true;
}
return false;
}
void handleMenuOption(MenuOption option)
{
switch (option)
{
case newGame:
std::cout << "Starting new game..." << std::endl;
break;
case loadGame:
std::cout << "Loading saved game..." << std::endl;
break;
case settings:
std::cout << "Opening settings..." << std::endl;
break;
case quit:
std::cout << "Goodbye!" << std::endl;
break;
}
}
int main()
{
std::string userInput;
MenuOption choice;
std::cout << "Main Menu (enter: new, load, settings, quit): ";
std::cin >> userInput;
if (stringToMenuOption(userInput, choice))
{
handleMenuOption(choice);
}
else
{
std::cout << "Invalid option: " << userInput << std::endl;
std::cout << "Please enter: new, load, settings, or quit" << std::endl;
}
return 0;
}
Example Output (with input "load"):
Main Menu (enter: new, load, settings, quit): Loading saved game...
Configuration file example
String conversion is useful when reading configuration from files:
#include <iostream>
#include <string>
enum LogLevel
{
debug,
info,
warning,
error
};
std::string logLevelToString(LogLevel level)
{
switch (level)
{
case debug: return "DEBUG";
case info: return "INFO";
case warning: return "WARNING";
case error: return "ERROR";
default: return "UNKNOWN";
}
}
bool stringToLogLevel(const std::string& str, LogLevel& level)
{
if (str == "DEBUG" || str == "debug")
{
level = debug;
return true;
}
else if (str == "INFO" || str == "info")
{
level = info;
return true;
}
else if (str == "WARNING" || str == "warning")
{
level = warning;
return true;
}
else if (str == "ERROR" || str == "error")
{
level = error;
return true;
}
return false;
}
void logMessage(LogLevel level, const std::string& message)
{
std::cout << "[" << logLevelToString(level) << "] " << message << std::endl;
}
int main()
{
// Simulate reading from config file
std::string configLogLevel = "warning";
LogLevel currentLogLevel;
if (stringToLogLevel(configLogLevel, currentLogLevel))
{
std::cout << "Log level set to: " << logLevelToString(currentLogLevel) << std::endl;
// Test logging
logMessage(info, "This is an info message"); // Won't show (below warning)
logMessage(warning, "This is a warning message"); // Will show
logMessage(error, "This is an error message"); // Will show
}
else
{
std::cout << "Invalid log level in config: " << configLogLevel << std::endl;
}
return 0;
}
Output:
Log level set to: WARNING
[WARNING] This is a warning message
[ERROR] This is an error message
Best practices for string conversion
1. Always provide a default case
std::string colorToString(Color color)
{
switch (color)
{
case red: return "red";
case green: return "green";
case blue: return "blue";
default: return "unknown"; // Always include this
}
}
2. Consider case-insensitive string matching
#include <algorithm>
#include <string>
bool stringToColorCaseInsensitive(std::string str, Color& color)
{
// Convert to lowercase
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
if (str == "red")
{
color = red;
return true;
}
// ... etc
return false;
}
3. Return success/failure status
// Good: returns whether conversion succeeded
bool stringToEnum(const std::string& str, EnumType& result);
// Less good: throws exception or returns invalid value
EnumType stringToEnum(const std::string& str);
4. Keep string representations consistent
// Good: consistent naming
enum NetworkState { disconnected, connecting, connected };
// Strings: "disconnected", "connecting", "connected"
// Confusing: inconsistent naming
enum NetworkState { offline, connecting, online };
// Don't use: "disconnected", "connecting", "connected"
Key concepts to remember
-
Direct enumeration printing shows integer values, not meaningful names.
-
Use switch statements to convert enumerations to strings.
-
String-to-enumeration conversion requires parsing and validation.
-
Always validate string input before converting to enumeration.
-
Consider using arrays for consecutive enumerations starting from 0.
-
Provide meaningful error handling for invalid conversions.
Summary
Converting enumerations to and from strings is essential for creating user-friendly interfaces and processing external data. While C++ doesn't provide automatic conversion, you can implement conversion functions using switch statements or array lookups. Always validate input when converting strings to enumerations, and consider case-insensitive matching for better user experience. These techniques make your enumerations much more practical for real-world applications.
Quiz
- Why doesn't printing an enumeration directly show its name instead of a number?
- What's the most common way to convert an enumeration to a string?
- Why should you always validate input when converting strings to enumerations?
- What are the advantages of using arrays for enumeration-string conversion?
- How can you make string-to-enumeration conversion more user-friendly?
Practice exercises
Try these exercises to practice enumeration-string conversion:
- Create an enumeration for planets in the solar system and functions to convert to/from strings.
- Write a program that reads day names (like "monday", "Tuesday") and converts them to a day-of-week enumeration.
- Create an enumeration for file types (.txt, .jpg, .pdf) with conversion functions that handle both uppercase and lowercase extensions.
- Build a simple command parser that converts user commands (like "help", "quit", "save") to an enumeration and executes appropriate actions.
Explore More Courses
Discover other available courses while this lesson is being prepared.
Browse CoursesLesson Discussion
Share your thoughts and questions