Hi I was trying to output unicode string to a console with iostreams and failed.
I found this: Using unicode font in c++ console app and this snippet works.
SetConsoleOutputCP(CP_UTF8);
wchar_t s[] = L"èéøÞǽлљΣæča";
int bufferSize = WideCharToMultiByte(CP_UTF8, 0, s, -1, NULL, 0, NULL, NULL);
char* m = new char[bufferSize];
WideCharToMultiByte(CP_UTF8, 0, s, -1, m, bufferSize, NULL, NULL);
wprintf(L"%S", m);
However, I did not find any way to output unicode correctly with iostreams. Any suggestions?
This does not work:
SetConsoleOutputCP(CP_UTF8);
utf8_locale = locale(old_locale,new boost::program_options::detail::utf8_codecvt_facet());
wcout.imbue(utf8_locale);
wcout << L"¡Hola!" << endl;
EDIT I could not find any other solution than to wrap this snippet around in a stream. Hope, somebody has better ideas.
//Unicode output for a Windows console
ostream &operator-(ostream &stream, const wchar_t *s)
{
int bufSize = WideCharToMultiByte(CP_UTF8, 0, s, -1, NULL, 0, NULL, NULL);
char *buf = new char[bufSize];
WideCharToMultiByte(CP_UTF8, 0, s, -1, buf, bufSize, NULL, NULL);
wprintf(L"%S", buf);
delete[] buf;
return stream;
}
ostream &operator-(ostream &stream, const wstring &s)
{
stream - s.c_str();
return stream;
}
The wcout must have the locale set differently to the CRT. Here's how it can be fixed:
I just tested it, and it displays the string here absolutely fine.
Unicode Hello World in Chinese
Here is a Hello World in Chinese. Actually it is just "Hello". I tested this on Windows 10, but I think it might work since Windows Vista. Before Windows Vista it will be hard, if you want a programmatic solution, instead of configuring the console / registry etc. Maybe have a look here if you really need to do this on Windows 7: Change console Font Windows 7
I dont want to claim this is the only solution, but this is what worked for me.
Outline
std::wcout
1 Project Setup
I am using Visual Studio 2017 CE. I created a blank console app. The default settings are alright. But if you experience problems or you use a different ide you might want to check these:
In your project properties find configuration properties -> General -> Project Defaults -> Character Set. It should be "Use Unicode Character Set" not "Multi-Byte". This will define
_UNICODE
andUNICODE
preprocessor macros for you.Also I think we should use
wmain
function instead ofmain
. They both work, but in a unicode environmentwmain
may be more convenient.Also my source files are UTF-16-LE encoded, which seems to be the default in Visual Studio 2017.
2. Console Codepage
This is quite obvious. We need the unicode codepage in the console. If you want to check your default codepage, just open a console and type
chcp
withou any arguments. We have to change it to 65001, which is the UTF-8 codepage. Windows Codepage Identifiers There is a preprocessor macro for that codepage:CP_UTF8
. I needed to set both, the input and output codepage. When I omitted either one, the output was incorrect.You might also want to check the boolean return values of those functions.
3. Choose a Font
Until yet I didnt find a console font that supports every character. So I had to choose one. If you want to output characters which are partly only available in one font and partly in another font, then I believe it is impossible to find a solution. Only maybe if there is a font out there that supports every character. But also I didnt look into how to install a font.
I think it is not possible to use two different fonts in the same console window at the same time.
How to find a compatible font? Open your console, go to the properties of the console window by clicking on the icon in the upper left of the window. Go to the fonts tab and choose a font and click ok. Then try to enter your characters in the console window. Repeat this until you find a font you can work with. Then note down the name of the font.
Also you can change the size of the font in the properties window. If you found a size you are happy with, note down the size values that are displayed in the properties window in the section "selected font". It will show width and height in pixels.
To actually set the font programmatically you use:
See my example at the end of this answer for details. Or look it up in the fine manual: SetCurrentConsoleFont. This function only exists since Windows Vista.
4. Set the locale
You will need to set the locale to the locale of the language which characters you want to print.
The return value is interesting. It will contain a string to describe exactly wich locale was chosen. Just give it a try :-) I tested with
chinese
andgerman
. More info: setlocale5. Use wide character output
Not much to say here. If you want to output wide characters, use this for example:
Oh, and dont forget the
L
prefix for wide characters! And if you type literal unicode characters like this in the source file, the source file must be unicode encoded. Like the default in Visual Studio is UTF-16-LE. Or maybe use notepad++ and set the encoding toUCS-2 LE BOM
.Example
Finally I put it all together as an example:
Cheers !
There are a few issues with the mswcrt and io streams.
Windows console supports UNICODE with the ReadConsole and WriteConsole functions in UTF-16LE mode. Background effect - piping in this case will not work. I.e. myapp.exe >> ret.log brings to 0 byte ret.log file. If you are ok with this fact you can try my library as following.
Library will auto-convert your UTF-8 into UTF-16LE and write it into console using WriteConsole. As well as there are error and input streams. Another library benefit - colors.
Link on example app: https://github.com/incoder1/IO/tree/master/examples/iostreams
The library homepage: https://github.com/incoder1/IO
Screenshot:
SetConsoleCP() and chcp does not the same!
Take this program snippet:
The source code must be saved as UTF-8 without BOM (Byte Order Mark; Signature). Then, the Microsoft compiler cl.exe takes the UTF-8 strings as-is.
If this code is saved with BOM, cl.exe transcodes the string to ANSI (i.e. CP1252), which doesn't match to CP65001 (= UTF-8).
Change the display font to Lucidia Console, otherwise, UTF-8 output will not work at all.
chcp
850
test.exe
tr├ñnen├╝berstr├ÂmtÔäó
chcp
65001
- This setting has changed bySetConsoleCP()
but with no useful effect.chcp 65001
test.exe
tränenüberströmt™
- All OK now.Tested with: German Windows XP SP3
Correctly displaying Western European characters in the windows console
Long story short:
chcp
to find which codepage works for you. In my case it waschcp 28591
for Western Europe.REG ADD HKCU\Console /v CodePage /t REG_DWORD /d 28591
History of the discovery
I had a similar problem, with Java. It is just cosmetic, since it involves log lines sent to the console; but it is still annoying.
The output from our Java application is supposed to be in UTF-8 and it displays correctly in eclipse's console. But in windows console, it just shows the ASCII box-drawing characters:
Inicializaci├│n
andartículos
instead ofInicialización
andartículos
.I stumbled upon a related question and mixed some of the answers to get to the solution that worked for me. The solution is changing the codepage used by the console and using a font that supports UNICODE (like
consolas
orlucida console
). The font you can select in the system menu of the Windows cosole:Win + R
then typecmd
and hit theReturn
key.Win
key and typecmd
followed by thereturn
key.Alt + Space
key combinationConsolas
orLucida console
OK
Regarding the codepage, for a one-off case, you can get it done with the command
chcp
and then you have to investigate which codepage is correct for your set of characters. Several answers suggested UTF-8 codepage, which is 65001, but that codepage didn't work for my Spanish characters.Another answer suggested a batch script to interactively selecting the codepage you wanted from a list. There I found the codepage for ISO-8859-1 I needed: 28591. So you could execute
before each execution of your application. You might check which code page is right for you in the Code Page Identifiers MSDN page.
Yet another answer indicated how to persist the selected codepage as the default for your windows console. It involves changing the registry, so consider yourself warned that you might brick your machine by using this solution.
This creates the
CodePage
value with the28591
data inside the HKCU\Console registry key. And that did work for me.Please note that HKCU ("HKEY_CURRENT_USER") is only for the current user. If you want to change it for all users in that computer, you'll need to use the
regedit
utility and find/create the correspondingConsole
key (probably you'll have to create aConsole
key insideHKEY_USERS\.DEFAULT
)I have verified a solution here using Visual Studio 2010. Via this MSDN article and MSDN blog post. The trick is an obscure call to
_setmode(..., _O_U16TEXT)
.Solution:
Screenshot: