C++ wchar_t* 到字符串的转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27720553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Conversion of wchar_t* to string
提问by Anas90
How can I convert an wchar_t*
array to an std::string
varStr in win32 console.
如何在 win32 控制台中将wchar_t*
数组转换为std::string
varStr。
回答by FelipeDurar
Use wstring, see this code:
使用wstring,看这个代码:
// 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;
回答by Norbert Willhelm
You should use the wstring class belonging to the namespace std. It has a constructor which accepts a parameter of the type wchar_t*.
您应该使用属于命名空间 std 的 wstring 类。它有一个构造函数,它接受一个 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.
您不必使用包含 String.begin() 和 String.end() 的构造函数,因为 std::wstring 的构造函数会自动分配用于存储 wchar_t 数组的内存并将该数组复制到分配的内存中。