0

I'm new to c++. I'm trying to change the color of some text based on what is read in from a config file.

The config file contains:

RED=DEFCOLOR

RED is defined in a header file:

static const std::string RED="\x1b[31m"; 

The code snippet in main()

while( std::getline(cfgin, cfgline)) {
    std::stringstream stream(cfgline);
    if( cfgline.find("DEFCOLOR") != string::npos) {
        std::stringstream stream(cfgline);
        getline(stream, DEFCOLOR, '=');
    }
}

DEFCOLOR now contains the text: RED.

Is there a way to actually use DEFCOLOR directly as if it were the value of RED defined in the header file so that executing:

cout << DEFCOLOR << "\n";

would be the equivalent of:

cout << RED << "\n";

which actually works? The former currently prints out the text: RED . I can get it to work by using a series of if statements to check the color:

if( DEFCOLOR == "RED") 
{
    cout << RED << "\n";
}

but there must be an better way.

jww
  • 97,681
  • 90
  • 411
  • 885
Art
  • 3
  • 4

1 Answers1

1

Use a map:

#include <map>

static const std::map<std::string, std::string> colors = {
    { "RED", "\x1b[31m" },
    { "BLUE", "..." },
    { "GREEN", "..." }
};

Then:

std::cout << colors[DEFCOLOR] << "\n";
Max Vollmer
  • 8,412
  • 9
  • 28
  • 43