Click here to Skip to main content
15,892,480 members
Articles / Programming Languages / C++

Unicode Output to the Windows Console

Rate me:
Please Sign up or sign in to vote.
4.11/5 (17 votes)
25 Mar 2009CPOL5 min read 152.2K   1.6K   35  
Working with Unicode strings in C++ and printing them to the Windows console
#pragma once
#include <iostream>
#include <windows.h>

std::ostream& operator<< (std::ostream& o, const wchar_t * const s) throw(...)
{
	const UINT cp = CP_UTF8;
	bool error = false;
	if (s)
	{
		int bufferSize = WideCharToMultiByte(cp, 0, s, -1, NULL,          0, NULL, NULL);
		char* m = new char[bufferSize];
		//Remember the old console codepage.
		UINT oldcp = GetConsoleOutputCP();
		//Change it to what we want.
		SetConsoleOutputCP (cp);
		/*            */ WideCharToMultiByte(cp, 0, s, -1,    m, bufferSize, NULL, NULL);
		if (o == std::cout) fwprintf(stdout, L"%S", m);
		else if (o == std::cerr) fwprintf(stderr, L"%S", m);
		else error = true;
		//It would be nice to have this instead, but unfortunately it does not work.
		//o << m;
		//Revert to the old codepage.
		SetConsoleOutputCP (oldcp);
		delete[] m;
	}
	else
	{
		//If s == NULL we must not try to convert with WideCharToMultiByte or we will get junk.
		//We go straight to fwprintf instead that prints "(null)" - We do not need to convert "(null)"
		//because there are no Unicode characters in it ;)
		if (o == std::cout) fwprintf(stdout, L"%s", s);
		else if (o == std::cerr) fwprintf(stderr, L"%s", s);
		else error = true;
	}
	if (error) throw "Not cout or cerr";
	return o;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Croatia Croatia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions