Windowsで文字コード変換するクラス。探したらいっぱい出てくるやつです。
EncodingConverter.h
#pragma once
#include <string>
class EncodingConverter
{
public:
static std::string SJISToUTF8(std::string src);
static std::string UTF8ToSJIS(std::string src);
};
EncodingConverter.cpp
#include "EncodingConverter.h"
#include <Windows.h>
#include <string>
#include <vector>
static std::wstring ConvertToUnicode(UINT cp, std::string src)
{
const DWORD dwFlags = 0;
const int srcLength = static_cast<int>(src.length());
const int dstLength = MultiByteToWideChar(cp, dwFlags, src.c_str(), srcLength, NULL, 0);
if (dstLength <= 0) return L"";
std::vector<wchar_t> dst(dstLength + 1);
MultiByteToWideChar(cp, dwFlags, src.c_str(), srcLength, &dst[0], dstLength);
return std::wstring(&dst[0], dstLength);
}
static std::string ConvertFromUnicode(UINT cp, std::wstring src)
{
const DWORD dwFlags = 0;
const int srcLength = static_cast<int>(src.length());
const int dstLength = WideCharToMultiByte(cp, dwFlags, src.c_str(), srcLength, NULL, 0, NULL, NULL);
if (dstLength <= 0) return "";
std::vector<char> dst(dstLength + 1);
WideCharToMultiByte(cp, dwFlags, src.c_str(), srcLength, &dst[0], dstLength, NULL, NULL);
return std::string(&dst[0], dstLength);
}
std::string EncodingConverter::SJISToUTF8(std::string src)
{
std::wstring unicode(ConvertToUnicode(CP_THREAD_ACP, src));
return std::string(ConvertFromUnicode(CP_UTF8, unicode));
}
std::string EncodingConverter::UTF8ToSJIS(std::string src)
{
std::wstring unicode(ConvertToUnicode(CP_UTF8, src));
return std::string(ConvertFromUnicode(CP_THREAD_ACP, unicode));
}