I've got a helper function that accepts a string and a vector of colors to use to format the string and right now my solution is to manually check the size of the color vector and call the console print with that same amount of colors.
Say I've got a color vector of 4, in the code it'd do something like:
void helper_func(TCODConsole* con, std::string msg_str, std::vector<TCOD_colctrl_t> color_vector)
{
char* message = msg_str.c_str();
//this is repeated 1 through 16, adding another color_vector.at(n) for each.
...
else if (color_vector.size() == 2)
//message might be "%cHello%c was in red"
console->print(x, y, message, color_vector.at(0), color_vector.at(1))
...
else if (color_vector.size() == 4)
//message might be "%cThe octopus%c shimmers at %cnight%c"
console->print(x, y, message, color_vector.at(0), color_vector.at(1), color_vector.at(2), color_vector.at(3))
...
}
While this works, it's awful and I was looking into different ways of pulling it off, allowing for more than 16 colors, etc.
I've tried doing a sprintf
for each color in the vector, adding it to the out_string and repeating. I've tried doing the same with an ostringstream. I've tried splitting the msg_str on "%c"
and then joining the resulting strings once I've added the color in to each. It never worked out, always either using the first color and then using random characters instead of colors from there on out.
I was hopeful that any of the above would work because simply sprintf(out_char, format_msg, TCOD_COLCTRL_1)
prints to the console (using console->print(out_char)
) just fine.
My question is: is there a good way to pass a varying number of colors to the console->print function and have it accurately display those colors, without severe code redundancy?
As a fallback, I could print out a section of the string up to the first color, calculate its size, move x
over by that much and print the next section, but that's not ideal.
I suppose that this question could be generalized to asking the same thing about regular printf
with substitutions too.