0

I know this is a simple question. But I want to cast enum value not red, blue but 0, 1, 2 etc to string. I want to see 0, 1, 2 as string. I am using c++ 14 compiler, any answer would be good.

#include <iostream>

int main()
{
    enum Color
    {
        red = 0,
        blue
    };

    Color color= Color::blue;

    std::string mystr = "I am super person my color enum value: ";
    mystr = mystr + color ;


    return 0;
}

Inother words I like to cast 0, 1, 2, as enum values to string. for concatenating with other strings

14
  • No. I want to print 0, 1, 2, 3, etc not the string as red blue.. My question so much more simple. Apr 10, 2020 at 14:07
  • 2
    Do you want std::to_string(static_cast<int>(color))?
    – Artyer
    Apr 10, 2020 at 14:08
  • this is the only way? do I have to use to_string? @Artyer Apr 10, 2020 at 14:09
  • @MericOzcan side note: use std::cout instead of printf
    – Moia
    Apr 10, 2020 at 14:11
  • What else do you want? With printf, you should do std::printf("%d", static_cast<int>(color)). With std::cout, you don't even need the cast (std::cout << color works fine)
    – Artyer
    Apr 10, 2020 at 14:11

3 Answers 3

0

An value of a plaint enum is just a int, so as pointed in the comments, it is the same of creating a std::string from int

#include <iostream>

int main()
{
    enum Color
    {
        red = 0,
        blue
    };

    Color color= Color::blue;

    std::string mystr = "I am super person my color enum value: ";
    mystr = mystr + std::to_string(color) ;

    std::cout << mystr;


    return 0;
}
0

To your enum as color specifier and use its attribute as name your have to use different data structure which can store color specified number and its name. For that problem you can use map to store color number and its name like following you can follow this URL to understand more about map URL: https://en.cppreference.com/w/cpp/container/map/map

int main()
{
    enum Color
    {
        red = 0,
        blue
    };

    std::map<int, std::string> map;
    map[0] = "red";
    map[1] = "blue";
    map[2] = "orange";

    Color color = Color::blue;

    printf("%s\n", map[color].c_str());
    //or
    cout << map[color] << endl;

    return 0;
}
0

I am also using a function like printf so std: cout might not be the answer here. Thank you for your help. I got my answer from the comments.

  #include <iostream>

int main()
{
    enum Color
    {
        red = 0,
        blue
    };

    Color color= Color::blue;

    std::string mystr = "I am super person my color enum value: ";
    mystr = mystr + std::to_string(static_cast<int>(color)) ;

    printf("%s", mystr);

    return 0;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.