Converting STL ANSI string to UNICODE string

STL supports both ANSI strings (string) and UNICODE strings (wstring) and declares them in <string>.
There are different approaches but I like something like this:

	#include <string>
	#include <algorithm>
	using namespace std;

	void __cdecl main(){
		string s;
		wstring w;

		//create locale
		std::locale loc("Russian");
		//select locale
		std::locale::global(loc);

		//set ANSI string contents
		s = "Some string with Cyrillic: рстуф";

		//reserve some space for UNICODE symbols
		w.resize(s.size());

		//apply btowc to all elements of ANSI string
		transform(s.begin(),s.end(),w.begin(),btowc);

		//print ANSI string
		printf("%s\n", s.c_str());

		//print UNICODE string
		wprintf(L"%s\n", w.c_str());
	}

Leave a Reply