Please do understand that this question is not a duplicate. There are questions out there with the same header :
However, I did some research before asking this question and came across ATL or Active Template Library.
However the compiler I use, doesn't come with ATL, which does not allow me to convert from LPCSTR
to LPCWSTR
.
Also, to understand why I need to convert these two datatypes, the reason is that I am working on a project, which is actually a Console Game Engine.
In case you don't know, to rename a console window, you need to use SetConsoleTitle(LPCWSTR winName)
And at first, I used LPCWSTR
datatype as an argument for my function. But, when I tried another function, which is actually a drawing function, this is what happens:
This combination of UNICODE
characters that you see here, is a function for drawing a rectangle on the console. The rectangle correctly displays, however, there is some text, or should I say, the Console Title itself, displayed across the rectangle.
I did not add any such thing of displaying the console title on the rectangle, nor did I mess up my code in any way. I burned through my code a few times, and there was nothing wrong, however, somehow, the console title is displayed on the rectangle.
I somehow think that this is related to the LPCWSTR datatype, because when I tried the function, SetConsoleTitle()
manually
Help me find a solution, will you?
Since the title is usually constant, you can simply call
SetConsoleTitle(L"My Title"); //or
const wchar_t* title = L"My Title";
SetConsoleTitle(title);
In general, use MultiByteToWideChar
to convert ANSI or UTF8, to UTF16
#include <iostream>
#include <string>
#include <windows.h>
std::wstring u16(const char* in, int codepage)
{
if (!in) return std::wstring(L"");
int size = MultiByteToWideChar(codepage, 0, in, -1, NULL, 0);
std::wstring ws(size, L'\0');
MultiByteToWideChar(codepage, 0, in, -1, ws.data(), size);
return ws;
}
int main()
{
const char* str = "My Title"; //<- ANSI string
SetConsoleTitle(u16(str, CP_ACP).c_str());
std::string s;
std::cin >> s;
str = reinterpret_cast<const char*>(u8"Ελληνικά"); //<- UTF8
SetConsoleTitle(u16(str, CP_UTF8).c_str());
std::cin >> s;
return 0;
}
Note that the title changes back when program exits.