您的位置:首页 > 其它

Unicode下wstring(wchar_t*)和string(char*)互相转换

2011-01-20 15:46 591 查看
1.#include

2.using namespace std;

3.

4.//将string转换成wstring

5.wstring string2wstring(string str)

6.{

7. wstring result;

8. //获取缓冲区大小,并申请空间,缓冲区大小按字符计算

9. int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0);

10. TCHAR* buffer = new TCHAR[len + 1];

11. //多字节编码转换成宽字节编码

12. MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len);

13. buffer[len] = '/0'; //添加字符串结尾

14. //删除缓冲区并返回值

15. result.append(buffer);

16. delete[] buffer;

17. return result;

18.}

19.

20.//将wstring转换成string

21.string wstring2string(wstring wstr)

22.{ 23. string result;

24. //获取缓冲区大小,并申请空间,缓冲区大小事按字节计算的

25. int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL);

26. char* buffer = new char[len + 1];

27. //宽字节编码转换成多字节编码

28. WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL);

29. buffer[len] = '/0';

30. //删除缓冲区并返回值

31. result.append(buffer);

32. delete[] buffer;

33. return result;

34.}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: