vs2015 如何把std::wstring转化为std::string字符串
时间: 2023-11-19 13:05:49 浏览: 38
可以使用WideCharToMultiByte函数将std::wstring转换为std::string字符串。具体实现可以参考以下代码:
```cpp
std::string WStringToString(const std::wstring& wstr)
{
int len = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
char* buffer = new char[len + 1];
memset(buffer, '\0', sizeof(char) * (len + 1));
WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, buffer, len, NULL, NULL);
std::string result(buffer);
delete[] buffer;
return result;
}
```
该函数将std::wstring转换为UTF-8编码的std::string字符串。需要注意的是,WideCharToMultiByte函数的第一个参数应该为CP_UTF8,表示使用UTF-8编码。
相关问题
std::wstring 转化std::string
可以使用下面的代码将 std::wstring 转换为 std::string:
```cpp
#include <locale>
#include <codecvt>
// Convert wstring to string
std::string wstring_to_string(const std::wstring& wstr)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
return converter.to_bytes(wstr);
}
```
使用方法:
```cpp
std::wstring wstr = L"Hello world!";
std::string str = wstring_to_string(wstr);
```
其中,std::codecvt_utf8 是一个标准库提供的 UTF-8 编码器,std::wstring_convert 可以将 wchar_t 类型的字符串转换为其他编码格式的字符串。
std::wstring out_wstring 转成std::string
可以使用std::wstring_convert类中的to_bytes()方法将std::wstring类型的字符串转换为std::string类型的字符串。具体实现方法如下所示:
```c++
std::wstring out_wstring = L"你好,世界!";
std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
std::string out_string = converter.to_bytes(out_wstring);
```
上述代码中,首先定义了一个std::wstring类型的字符串out_wstring,然后创建了一个std::wstring_convert对象converter,并指定了其模板参数为std::codecvt_utf8<wchar_t>,表示使用UTF-8编码。最后调用converter对象的to_bytes()方法将out_wstring转换为std::string类型的字符串out_string。