stringとwcharの変換

自分用メモ。

ああああ、C++で文字列めんどくせえええ。

#include <iostream>
#include <string>
#include <vector>
#include <locale>
#include <cstdlib>

using namespace std;

void narrow(const std::wstring &src, std::string &dest) {
	char *mbs = new char[src.length() * MB_CUR_MAX + 1];
	wcstombs(mbs, src.c_str(), src.length() * MB_CUR_MAX + 1);
	dest = mbs;
	delete [] mbs;
}

void widen(const std::string &src, std::wstring &dest) {
	wchar_t *wcs = new wchar_t[src.length() + 1];
	mbstowcs(wcs, src.c_str(), src.length() + 1);
	dest = wcs;
	delete [] wcs;
}

std::string head(std::string str) {
  std::wstring wstr;
  widen(str, wstr);
  std::string result;
  std::wstring tmp;
  tmp = wstr[0];
  narrow(tmp, result);
  return result;
}

std::string tail(std::string str) {
  std::wstring wstr;
  widen(str, wstr);
  std::string result;
  std::wstring tmp;
  tmp = wstr[wstr.size()-1];
  narrow(tmp, result);
  return result;
}

int main(int argc, char *argv[]) {
  setlocale(LC_CTYPE, "");
  std::string str   = "日本語";
  std::cout << head(str) << std::endl; 
  std::cout << tail(str) << std::endl; 
}