如何将 wstring 转换为字符串?
问题是如何将wstring转成字符串?
The question is how to convert wstring to string?
我有下一个例子:
#include <string>
#include <iostream>
int main()
{
std::wstring ws = L"Hello";
std::string s( ws.begin(), ws.end() );
//std::cout <<"std::string = "<<s<<std::endl;
std::wcout<<"std::wstring = "<<ws<<std::endl;
std::cout <<"std::string = "<<s<<std::endl;
}
带有注释行的输出是:
std::string = Hello
std::wstring = Hello
std::string = Hello
但没有只是:
std::wstring = Hello
这个例子有什么问题吗?我可以像上面那样进行转换吗?
Is anything wrong in the example? Can I do the conversion like above?
编辑
新的例子(考虑到一些答案)是
New example (taking into account some answers) is
#include <string>
#include <iostream>
#include <sstream>
#include <locale>
int main()
{
setlocale(LC_CTYPE, "");
const std::wstring ws = L"Hello";
const std::string s( ws.begin(), ws.end() );
std::cout<<"std::string = "<<s<<std::endl;
std::wcout<<"std::wstring = "<<ws<<std::endl;
std::stringstream ss;
ss << ws.c_str();
std::cout<<"std::stringstream = "<<ss.str()<<std::endl;
}
输出是:
std::string = Hello
std::wstring = Hello
std::stringstream = 0x860283c
因此不能使用字符串流将 wstring 转换为字符串.
therefore the stringstream can not be used to convert wstring into string.
推荐答案
以下是根据其他建议制定的解决方案:
Here is a worked-out solution based on the other suggestions:
#include <string>
#include <iostream>
#include <clocale>
#include <locale>
#include <vector>
int main() {
std::setlocale(LC_ALL, "");
const std::wstring ws = L"???l?";
const std::locale locale("");
typedef std::codecvt<wchar_t, char, std::mbstate_t> converter_type;
const converter_type& converter = std::use_facet<converter_type>(locale);
std::vector<char> to(ws.length() * converter.max_length());
std::mbstate_t state;
const wchar_t* from_next;
char* to_next;
const converter_type::result result = converter.out(state, ws.data(), ws.data() + ws.length(), from_next, &to[0], &to[0] + to.size(), to_next);
if (result == converter_type::ok or result == converter_type::noconv) {
const std::string s(&to[0], to_next);
std::cout <<"std::string = "<<s<<std::endl;
}
}
这通常适用于 Linux,但会在 Windows 上产生问题.
This will usually work for Linux, but will create problems on Windows.
相关文章