Created
November 12, 2014 05:37
-
-
Save takamin/2752a45c5cb4d0f9d1ff to your computer and use it in GitHub Desktop.
convert Shift-JIS string to utf-8 on Visual C++ (Microsoft Visual Studio Express 2013 for Windows Desktop)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "stdafx.h" | |
#include <string> | |
//VC++ SJIS string を utf-8のstringに変換する | |
string sjis2utf8(const string& sjis) { | |
string utf8_string; | |
//一旦SJISからutf-16へ変換 | |
LPCCH pSJIS = (LPCCH)sjis.c_str(); | |
int utf16size = ::MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, pSJIS, -1, 0, 0); | |
if (utf16size != 0) { | |
LPWSTR pUTF16 = new WCHAR[utf16size]; | |
if (::MultiByteToWideChar(CP_ACP, 0, (LPCCH)pSJIS, -1, pUTF16, utf16size) != 0) { | |
//次にutf-16からutf-8へ変換 | |
int utf8size = ::WideCharToMultiByte(CP_UTF8, 0, pUTF16, -1, 0, 0, 0, 0); | |
if (utf8size != 0) { | |
LPTSTR pUTF8 = new TCHAR[utf8size + 16]; | |
ZeroMemory(pUTF8, utf8size + 16); | |
if (::WideCharToMultiByte(CP_UTF8, 0, pUTF16, -1, pUTF8, utf8size, 0, 0) != 0) { | |
utf8_string = string(pUTF8); | |
} | |
delete pUTF8; | |
} | |
} | |
delete pUTF16; | |
} | |
return utf8_string; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It'll be better replace CP_ACP as 932.
because if your host windows not japanese charset but chinese, CP_ACP is ANSI default, the convertion will failed.