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

来源:互联网 发布:卖家淘宝客如何推广 编辑:程序博客网 时间:2024/05/21 13:58

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.}