c++ string and wstring conversion

wchar_t to char

#include <comdef.h>

const wchar_t* exepath = L"d:\\中文 路径\\中文 路径.exe";
_bstr_t b(exepath);
const char* c = b;
printf("%s\n", c);

MultiByteToWideChar string to wstring

  setlocale(LC_ALL, "chs");
  string s1 = "中文 こんにちは";

  size_t wstr_size = MultiByteToWideChar(CP_ACP, 0, s1.c_str(), s1.length(), NULL, NULL);
  if (wstr_size == NULL) return 0;

  wstring s2;
  s2.resize(wstr_size);

  MultiByteToWideChar(CP_ACP, 0, s1.c_str(), s1.length(), (LPWSTR)s2.data(), s2.length());

  printf("%s\n", s1.c_str());
  printf("%ls\n", s2.c_str());

WideCharToMultiByte wstring to string

  setlocale(LC_ALL, "chs");
  wstring s1 = L"中文 こんにちは";

  size_t str_size = WideCharToMultiByte(CP_ACP, 0, s1.data(), s1.length(), NULL, NULL, 0, 0);
  if (str_size == NULL) return 0;

  string s2;
  s2.resize(str_size);

  WideCharToMultiByte(CP_ACP, 0, s1.data(), s1.length(), (LPSTR)s2.data(), s2.length(), 0, 0);

  printf("%ls\n", s1.c_str());
  printf("%s\n", s2.c_str());
  return 0;

posted @ 2020-08-30 17:09  Ajanuw  阅读(57)  评论(0编辑  收藏  举报