6

I have problems with outputing unicode characters in Windows console. I am using Windows XP and Code Blocks 12.11 with mingw32-g++ compiler.

What is the proper way to output unicode characters in Windows console with C or C++?

This is my C++ code:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    cout << "šđč枊ĐČĆŽ" << endl; // doesn't work

    string s = "šđč枊ĐČĆŽ";
    cout << s << endl;            // doesn't work

    return 0;
}

Thanks in advance. :)

1 Answers1

11

Most of those characters take more than a byte to encode, but std::cout's currently imbued locale will only output ASCII characters. For that reason you're probably seeing a lot of weird symbols or question marks in the output stream. You should imbue std::wcout with a locale that uses UTF-8 since these characters are not supported by ASCII:

// <locale> is required for this code.

std::locale::global(std::locale("en_US.utf8"));
std::wcout.imbue(std::locale());

std::wstring s = L"šđč枊ĐČĆŽ";
std::wcout << s;

For Windows systems you will need the following code:

#include <iostream>
#include <string>
#include <fcntl.h>
#include <io.h>

int main()
{      
    _setmode(_fileno(stdout), _O_WTEXT);

    std::wstring s = L"šđč枊ĐČĆŽ";
    std::wcout << s;

    return 0;
}
David G
  • 94,763
  • 41
  • 167
  • 253
  • Thanks for your answer, but I still have problem. If I run your code i get message "terminate called after throwing an instance of 'std::runtime_error' what(): locale::facet::_S_create_c_locale name not valid" –  Jul 14 '13 at 18:12
  • @user2581142 What OS are you running this on (Linux, Windows, etc.)? – David G Jul 14 '13 at 18:12
  • I am using Virtual Windows XP on my Linux Mint 14. –  Jul 14 '13 at 18:14
  • @user2581142 Windows doesn't interpret Unicode in the same way as other OSs. You'll need to use a different approach which I will show in my update. – David G Jul 14 '13 at 18:17
  • Thank you, it is finnaly working. I needed to change console font to "Lucida Console" and it is working in Micosoft Visual Studio 2010 as Win32 Console Application. It is not working in Code Blocks 12.11. –  Jul 14 '13 at 19:09
  • @user2581142 Great! Did you use `_setmode` (I made a typo in my code, I gave it two underscores `__setmode` instead of one lol) – David G Jul 14 '13 at 19:12
  • Yes, I used `_setmode`. –  Jul 14 '13 at 19:17