How to use the WriteConsoleOutputAttribute function correctly
Why the following code
const std::string text = "str";
HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD coords = { 0, 0 };
DWORD written = 0;
WriteConsoleOutputCharacterA(stdout_handle, text.c_str(), text.size(), coords, &written);
WORD attributes = FOREGROUND_GREEN;
WriteConsoleOutputAttribute(stdout_handle, &attributes, text.size(), coords, &written);
results in the following:
What am I doing wrong? How can I fix this?
+3
source to share
1 answer
&attributes
indicates an array of length one, one green attribute. But you are claiming that the array is text.size()
long. As a result, you copy the contents of the random stack into the next 2 cells. It looks red and red.
Decision:
std::vector<WORD> attributes(text.size(), FOREGROUND_GREEN);
WriteConsoleOutputAttribute(stdout_handle, &attributes[0] ...
+7
source to share