わびさびサンプルソース

WindowsやHTML5などのプログラムのサンプルコードやフリーソフトを提供します。

wstringをstringへ変換する

string変換する為には、WideCharToMultiByte()関数を使用します。第1引数にCP_OEMCPを渡す事でUCS2文字列を扱う事ができます。

#include <stdio.h>
#include <tchar.h>
#include <locale.h>
#include <string>
#include <iostream>
#include <windows.h>



/*
	wstringをstringへ変換
*/
std::string WStringToString
(
	std::wstring oWString
)
{
	// wstring → SJIS
	int iBufferSize = WideCharToMultiByte( CP_OEMCP, 0, oWString.c_str()
		, -1, (char *)NULL, 0, NULL, NULL );

	// バッファの取得
	CHAR* cpMultiByte = new CHAR[ iBufferSize ];

	// wstring → SJIS
	WideCharToMultiByte( CP_OEMCP, 0, oWString.c_str(), -1, cpMultiByte
		, iBufferSize, NULL, NULL );

	// stringの生成
	std::string oRet( cpMultiByte, cpMultiByte + iBufferSize - 1 );

	// バッファの破棄
	delete [] cpMultiByte;

	// 変換結果を返す
	return( oRet );
}





int _tmain
(
	  int argc
	, _TCHAR* argv[]
)
{
	/*
		ロケールを日本に設定
		 これを設定するだけで、標準出力に日本語が表示される
		 ようになります。
	*/
	setlocale( LC_ALL, "Japanese" );

	// wstringをstringへ変換
	std::string str = WStringToString( L"あいうえお¥n" );

	// 標準出力へ出力する
	std::cout << str << std::endl;

	// 正常終了
	return( 0 );
}

実行結果

あいうえお






わびさびサンプルソース

WindowsやHTML5などのプログラムのサンプルコードやフリーソフトを提供します。