I recently got back into C++ and this is just beyond me. This cmd app, when compiled using the debugger in VS2022, looks perfectly as it should. However, when I run the compiled project executable, a seemingly random piece of text often changes its color to the default white.
It's obviously not noticeable when it happens with white text, but I intend to use SetConsoleTextAttribute (or any other way to print colored text) in my program, as well as Unicode support, which _getline does just fine.
It appears to be caused by wcout, as removing _setline and changing them back to the narrow type fixed the issue. However, just removing _setline doesn't do anything.
Code:
#include <iostream>
#include <fcntl.h>
#include <Windows.h>
#include <io.h>
using namespace std;
int main() {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
fflush(stdout);
(void)_setmode(_fileno(stdout), _O_U16TEXT);
SetConsoleTextAttribute(hConsole, 10);
wcout << L"Lorem ipsum dolor sit amet, consectetur adipiscing elit,\n";
wcout << L"sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n";
SetConsoleTextAttribute(hConsole, 11);
wcout << L"Lorem ipsum dolor sit amet, consectetur adipiscing elit,\n";
wcout << L"sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n";
SetConsoleTextAttribute(hConsole, 12);
wcout << L"Lorem ipsum dolor sit amet, consectetur adipiscing elit,\n";
wcout << L"sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n";
cin.get();
}
EDIT: Using wmain instead of main and calling fflush wherever it made the tiniest bit of sense didn't fix anything either. Weird.
I seem to have fixed it, Using wmain instead of _setline. setting locale to "" at the beginning and flushing stdout before main returns 0 makes the problem disappear with Unicode still being supported.
Like this:
#include <iostream>
#include <locale>
#include <Windows.h>
using namespace std;
int wmain() {
setlocale(LC_ALL, "");
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, 10);
wprintf(L"Lorem ipsum dolor sit amet, consectetur adipiscing elit,\n");
wprintf(L"sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n");
SetConsoleTextAttribute(hConsole, 11);
wprintf(L"Lorem ipsum dolor sit amet, consectetur adipiscing elit,\n");
wprintf(L"sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n");
SetConsoleTextAttribute(hConsole, 12);
wprintf(L"Lorem ipsum dolor sit amet, consectetur adipiscing elit,\n");
wprintf(L"sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n");
cin.get();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.