首页 > 编程语言 > 详细

VC++中 wstring和string的互相转换实现

时间:2014-01-21 16:29:31      阅读:387      评论:0      收藏:0      [点我收藏+]

在VC++开发中,经常会用到string和wstring,这就需要二者之间的转换,项目中封装了wstring和string相互转换的2个函数,实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//将wstring转换成string
std::string ConvertWStringToAnsi(std::wstring wstr)
{
    std::string result;
    int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL);
    if( len <= 0 )
        return result;
 
    char* buffer = new char[len + 1];
    if(buffer == NULL )
        return result;
 
    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL);
    buffer[len] = ‘\0‘;               //字符串断尾
    result.append(buffer);            //赋值
    delete[] buffer;                  //删除缓冲区
 
    //返回值
    return result;
}
 
 
//将string转换成wstring
std::wstring ConvertAnsiToWString(std::string str)
{
    std::wstring result;
 
    int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0);
    if( len < 0 )
        return result;
 
    wchar_t* buffer = new wchar_t[len + 1];
    if( buffer == NULL )
        return result;
 
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len);
 
    buffer[len] = ‘\0‘;                    //字符串断尾
    result.append(buffer);                 //赋值
    delete[] buffer;                       //删除缓冲区
 
    //返回值
    return result;
}

  

VC++中 wstring和string的互相转换实现

原文:http://www.cnblogs.com/JczmDeveloper/p/3527189.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!