What is garbage in c

Converting Enum to String in C ++

  1. How-To's
  2. C ++ instructions
  3. Converting Enum to String in C ++

Created: November-05, 2020

  1. Use an array to convert an enumeration to a string in C ++
  2. Use a user-defined function to convert an enumeration to a string in C ++

This article explains several methods of converting an enumeration type to a string variable in C ++.

Use an array to convert an enumeration to a string in C ++

is a built-in type that can be used to declare small named integers, usually formed as an array. This mechanism offers a less error-prone and more readable way of representing a set of integer values.

Enumerated items can have a position value (as has in our example code) or they can have an explicit value (declared as).

This example shows how implicit values ​​of elements can be used to access corresponding string values ​​from an array. Notice that at the beginning of the main function we are initializing a random input variable with the value from the range 1-4 to better illustrate the real world scenario.

Output:

Use a user-defined function to convert an enumeration to a string in C ++

Alternatively, we can define our own function that takes an integer as a parameter and returns a string value. The character string variable is initialized with a value from the array within the function. If you pass this as an argument to the function, it will return a garbage value because the array only has 4 elements.

Output:

The inclusion of the element in the above type can have practical uses. For one, it represents the number of items in the enumeration that can be used as loop parameters, as shown in the sample code below. The first loop extracts each string from the array and shifts it into the vector variable. The second iteration outputs the content of to the console.

Output: