Conversion of wchar_t* to string [duplicate]

感情迁移 提交于 2019-12-05 10:00:29

问题


How can I convert an wchar_t* array to an std::string varStr in win32 console.


回答1:


Use wstring, see this code:

// Your wchar_t*
wchar_t* txt = L"Hello World";
wstring ws(txt);
// your new String
string str(ws.begin(), ws.end());
// Show String
cout << str << endl;



回答2:


You should use the wstring class belonging to the namespace std. It has a constructor which accepts a parameter of the type wchar_t*.

Here is a full example of using this class.

wchar_t* characters=L"Test";
std::wstring string(characters);

You do not have to use a constructor containing String.begin() and String.end() because the constructor of std::wstring automatically allocates memory for storing the array of wchar_t and copies the array to the allocated memory.



来源:https://stackoverflow.com/questions/27720553/conversion-of-wchar-t-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!