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.

0

1 Answer 1

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";
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Max! That worked well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.