UTF8変換する為には、WideCharToMultiByte()関数を使用します。第1引数にCP_UTF8を渡す事でUTF8文字列を扱う事ができます。
#include <stdio.h>
#include <tchar.h>
#include <locale.h>
#include <string>
#include <iostream>
#include <windows.h>
/*
wstringをUTF8文字列に変換する
*/
std::string WStringToUtf8
(
std::wstring oWString
)
{
// wstring → UTF8
int iBufferSize = ::WideCharToMultiByte( CP_UTF8, 0, oWString.c_str()
, -1, (char *)NULL, 0, NULL, NULL );
// バッファの取得
CHAR* cpBufUTF8 = new CHAR[ iBufferSize ];
// wstring → UTF8
::WideCharToMultiByte( CP_UTF8, 0, oWString.c_str(), -1, cpBufUTF8
, iBufferSize, NULL, NULL );
// stringの生成
std::string oRet( cpBufUTF8, cpBufUTF8 + iBufferSize - 1 );
// バッファの破棄
delete [] cpBufUTF8;
// 変換結果を返す
return( oRet );
}
int _tmain
(
int argc
, _TCHAR* argv[]
)
{
// 標準出力にユニコード出力する
setlocale( LC_ALL, "Japanese" );
// wstringをUTF8文字列に変換する
std::string oString = WStringToUtf8( L"wstring to UTF8" );
// 標準出力へ出力する
std::cout << oString << std::endl;
// 正常終了
return( 0 );
}
wstring to UTF8