stl中char 与wchar 的转换

学习记录:

stl中 字符串 str自然对应的是string

宽字符串wchar 对应的是wstring

宽字符串占用两个字节

两者的转换有三种办法

1 windows 的api转换函数WideCharToMultiByte()与MultiByteToWideChar(). 不适合跨平台使用.

2 ATL中CA2W类与CW2A类。或者使用A2W宏与W2A宏。稍显累赘和麻烦

3 使用CRT库的函数 函数和使用方法见下列代码

#include <string>
#include <iostream>
#include <locale.h>

using namespace std;


string ws2s(const wstring &ws)
{
    const wchar_t* wpchar = ws.c_str();
    size_t returnVal = 0;
    size_t wSize = 2*ws.size() + 1;
    char* pchar = new char[wSize];
    memset(pchar,0,wSize);
    wcstombs_s(&returnVal,pchar,wSize,wpchar,wSize);
    string result = pchar;
    delete[] pchar;
    return result;
}


int _tmain(int argc, _TCHAR* argv[])
{
    setlocale(LC_ALL,"chs");

    wstring ws = L"中国 你好,sf*&%*&^%^&sd,这是一个测试";
    string ss = ws2s(ws);

    wcout << ws << endl;
    cout << ss << endl;

    return 0;
}
原文地址:https://www.cnblogs.com/itdef/p/4143917.html