1

I have actually an enum in c++:

class myClass
{
public:
    enum ExampleType
    {
       TEST1
       TEST2
       TEST3
       TEST4
    }
};

I would like to print the enum not as number but as String.. Actually it prints 0 .. 1 .. 2 .. 3 I would like it print TEST1 or TEST2 etc ...

I already try Switch case as :

 std::string type;
  switch (this->type)
    {
    case 0:   type = "TEST1";
    case 1:   type = "TEST2";
    case 2: type = "TEST3";
    case 3: type = "TEST4";
    }

then print type, but he don't go in the right case ..

How can it be possible ?

Laykker
  • 322
  • 1
  • 3
  • 12

4 Answers4

3

In C/C++, case statements fall through. You must use break to exit the switch statement. If your this->type is 0, then the code that is executed is:

type = "TEST1";
type = "TEST2";
type = "TEST3";
type = "TEST4";

What you want is:

switch( this->type )
{
case TEST1: type = "TEST1";
            break;
case TEST2: type = "TEST2";
            break;
//...
}

Or, if you have a function that is returning this value, simply return the value:

std::string type_string()
{
    switch( this->type )
    {
    case TEST1: return "TEST1";
    case TEST2: return "TEST2";
    //...
    default:    return std::string::empty();
    }
}

Note: (Since @DoxyLover's comment) I changed the switch to use the declared enum constants as you should use these instead. If someone added a TEST0 to the start of the enum, then the switch statement will still execute correctly, while your version would not.

clcto
  • 9,530
  • 20
  • 42
2

In addition to the other answers, you can also do something like this: (C99)

#include <ansi_c.h>

enum ExampleType
{
    TEST1,
    TEST2,
    TEST3,
    TEST4,
    TEST_MAX
};

const char string[TEST_MAX][10]={"TEST1","TEST2","TEST3","TEST4"};


int main(void)
{
    int i;
    for(i=0;i<TEST_MAX;i++)
    {
        printf("%d: %s\n", i, string[i]);   
    }

    return 0;
}
ryyker
  • 22,849
  • 3
  • 43
  • 87
1

In switch-case statements, evaluation falls through between the cases. This is what makes it unique from if-else where the key word "else" assures that only one set of instructions is chosen. Add a break at the end of each case to prevent this as good practice.

Chris Zhang
  • 968
  • 7
  • 16
1

If you know what you want to print at compile time, you can use the preprocessor like this:

Code

#define STRINGIFY(word) (#word)

int main(void)
{
    printf("%d %s\n", TEST2, STRINGIFY(TEST2)); 

    return 0;
}

Output

1 TEST2

Big But

However, this is really no different than doing this:

printf("%d TEST2\n", TEST2);
Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46