您当前的位置: 首页 >  c++

令狐掌门

暂无认证

  • 0浏览

    0关注

    513博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

C++各种数据类型转换

令狐掌门 发布时间:2020-03-03 16:10:46 ,浏览量:0

1. 将string转换成wstring

#include 

wstring string2wstring(string str)  
{  
    wstring result;  
    //获取缓冲区大小,并申请空间,缓冲区大小按字符计算  
    int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0);  
    TCHAR* buffer = new TCHAR[len + 1];  
    //多字节编码转换成宽字节编码  
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len);  
    buffer[len] = '\0';             //添加字符串结尾  
    //删除缓冲区并返回值  
    result.append(buffer);  
    delete[] buffer;  
    return result;  
}  

2. 将wstring转换成string

//将wstring转换成string  
string wstring2string(wstring wstr)  
{  
    string result;  
    //获取缓冲区大小,并申请空间,缓冲区大小事按字节计算的  
    int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL);  
    char* buffer = new char[len + 1];  
    //宽字节编码转换成多字节编码  
    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL);  
    buffer[len] = '\0';  
    //删除缓冲区并返回值  
    result.append(buffer);  
    delete[] buffer;  
    return result;  
} 

3 string转const char *

string str;
const char *cstr = str.c_str();

4 其它类型转LPCWSTR

   这种用wstring可以直接转,例如   

wstring  wstr = "qwqwq";

LPCWSTR lpcw = wstr.c_str().

   只要把其它类型转为wstring即可,Qt, CString都可以转。

关注
打赏
1652240117
查看更多评论
立即登录/注册

微信扫码登录

0.0387s