我怎样才能得到一个std::wstring
其中包括一些非ASCII字符的字符串?
下面的代码无法正常输出: (该文本是一个阿拉伯字包含4个字符,其中每个字符有两个字节,加上单词“hello”)
#include <iostream>
#include <string>
using namespace std;
int main()
{
wstring s = L"سلام hello";
wcout << s.substr(0,3) << endl;
wcout << s.substr(4,5) << endl;
return 0;
}
这应该工作:live on Coliru
#include <iostream>
#include <string>
#include <boost/regex/pending/unicode_iterator.hpp>
using namespace std;
template <typename C>
std::string to_utf8(C const& in)
{
std::string result;
auto out = std::back_inserter(result);
auto utf8out = boost::utf8_output_iterator<decltype(out)>(out);
std::copy(begin(in), end(in), utf8out);
return result;
}
int main()
{
wstring s = L"سلام hello";
auto first = s.substr(0,3);
auto second = s.substr(4,5);
cout << to_utf8(first) << endl;
cout << to_utf8(second) << endl;
}
打印
سلا
hell
坦率地说,虽然,我认为你的substring
呼叫正在奇怪的假设。让我提出一个修补程序在一分钟内: