I'm trying to create a basic console C++ loading program (to be a part of a larger console C++ project I'm working on) and I can't seem to get setConsoleTextAttribute to work correctly.
My code is compiling just fine without error in Code::Blocks so I don't know what the problem is.
In loadTextColor() the set color "green" will not load even if they file holds a value equal to "1." It will instead default to a "blue" color (which requires a value in text.txt equal to "2").
In loadBackgroundColor() the backgrounds will not load at all.
If I'm missing some obvious handle declaration or something please tell me. Tinkered with this over a few hours and I can't seem to identify the problem
setConsoleTextAttribute sets both foreground and background colors simultaneously, so if you call it twice, one will overwrite the other.
I don't see why you'd get the wrong color though. Could it be that you gave wrong values to FOREGROUND_GREEN and etc. ? (Post their definitions)
Why do you need to add indirection nike that? Just store the colors in the file directly, then just validate that they are in an appropriate range when you load them.
Your program's organization seems off also. And why are there two files just for a single color value each? Why are you chaining procedures like that?
Why are you clearing the screen at the end of every function? And why are you using system() to do it?
myprog.cfg
# configuration file for MyProg
bg color
3
fg color
14
void loadConfig( constchar* filename = DEFAULT_CONFIG_FILENAME )
{
ifstream f(filename);
if (!f) return;
WORD bgcolor = 0x100;
WORD fgcolor = 0x100;
string s;
while (getline(f, s))
{
// Skip blank lines and lines with comments
size_t n = s.find_first_not_of(" \t");
if ((n > s.length()) or (s[ n ] == '#'))
{
continue;
}
// Recognize and load options
if (s == "bg color")
{
unsigned color;
f >> color;
f.ignore(numeric_limits<streamsize>::max(), '\n');
if ((color < 16) && (color != fgcolor))
{
bgcolor = color;
}
}
elseif (s == "fg color")
{
unsigned color;
f >> color;
f.ignore(numeric_limits<streamsize>::max(), '\n');
if ((color < 16) && (color != bgcolor))
{
fgcolor = color;
}
}
elseif (s == "...")
{
// other options are handled the same way
...
}
else
{
// unrecognized options are ignored
f.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
// Set those options (like text colors) that were not set above (like ...)
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), (bgcolor << 4) | fgcolor);
...
}
This is a very simple setup. The beginning of your program, of course, preserves the current state and sets default options before calling the load function, something like: