#3
by ISLe » 8年前
Visual StudioのIDEが文字として認識するのは、ワイド文字(wchar_t)かANSI文字(char)です。
std::stringはANSI文字対応なので、ANSI文字列に変換する必要があります。
文字コードの変換に言語レベルでの標準は無く、下記はWin32 APIを使う場合の例です。
コード:
#include <string>
#include <iostream>
#include <windows.h>
int main()
{
char buf_utf8[] = u8"あいうえお";
wchar_t buf_wc[256];// = L"あいうえお";
char buf_ansi[256];// = "あいうえお";
// UTF-8文字列からワイド文字列へ変換
MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, buf_utf8, -1, buf_wc, 256);
// ワイド文字列からANSI(CP932)文字列へ変換
WideCharToMultiByte(CP_ACP, 0, buf_wc, -1, buf_ansi, 256, nullptr, nullptr);
std::string str(buf_ansi);
std::cout << str << std::endl;
return 0;
}
Visual StudioのIDEが文字として認識するのは、ワイド文字(wchar_t)かANSI文字(char)です。
std::stringはANSI文字対応なので、ANSI文字列に変換する必要があります。
文字コードの変換に言語レベルでの標準は無く、下記はWin32 APIを使う場合の例です。
[code=cpp]#include <string>
#include <iostream>
#include <windows.h>
int main()
{
char buf_utf8[] = u8"あいうえお";
wchar_t buf_wc[256];// = L"あいうえお";
char buf_ansi[256];// = "あいうえお";
// UTF-8文字列からワイド文字列へ変換
MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, buf_utf8, -1, buf_wc, 256);
// ワイド文字列からANSI(CP932)文字列へ変換
WideCharToMultiByte(CP_ACP, 0, buf_wc, -1, buf_ansi, 256, nullptr, nullptr);
std::string str(buf_ansi);
std::cout << str << std::endl;
return 0;
}
[/code]