C++无法将字符串转换为wstring

标签 c++ linux special-characters substr wstring

我想将字符串变量转换为 wstring,因为某些德语字符在对变量执行 substr 时会导致问题。当任何这些特殊字符出现在起始位置之前时,起始位置就会被伪造。 (例如:对于 "ä"size() 返回 2 而不是 1)

我知道以下转换有效:

wstring ws = L"ä";

因为,我正在尝试转换一个变量,我想知道是否有其他方法,例如

wstring wstr = L"%s"+str //this is syntaxically wrong, but wanted sth alike

除此之外,我已经尝试了以下 example将字符串转换为 wstring:

string foo("ä"); 
wstring_convert<codecvt_utf8<wchar_t>> converter;
wstring wfoo = converter.from_bytes(foo.data());
cout << foo.size() << endl;
cout << wfoo.size() << endl;

,但我收到类似

的错误
‘wstring_convert’ was not declared in this scope

我使用的是 ubuntu 14.04,我的 main.cpp 是用 cmake 编译的。感谢您的帮助!

最佳答案

“hahakubile”的解决方案对我有用:

std::wstring s2ws(const std::string& s) {
    std::string curLocale = setlocale(LC_ALL, ""); 
    const char* _Source = s.c_str();
    size_t _Dsize = mbstowcs(NULL, _Source, 0) + 1;
    wchar_t *_Dest = new wchar_t[_Dsize];
    wmemset(_Dest, 0, _Dsize);
    mbstowcs(_Dest,_Source,_Dsize);
    std::wstring result = _Dest;
    delete []_Dest;
    setlocale(LC_ALL, curLocale.c_str());
    return result;
}

但是返回值并不是100%正确的:

string s = "101446012MaßnStörfall   PAt  #Maßnahme Störfall                      00810000100121000102000020100000000000000";
wstring ws2 = s2ws(s);
cout << ws2.size() << endl; // returns 110 which is correct
wcout << ws2.substr(29,40) << endl; // returns #Ma�nahme St�rfall with symbols

我想知道为什么它用符号代替了德语字符。

再次感谢!

关于C++无法将字符串转换为wstring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25141848/

相关文章:

css - 特殊字符的字体大小 css 不正确

c++ - Boost::Spirit 简单语法示例

c++ - 在同一语句中调用的 IO 执行函数 : Undefined or unspecified?

c++ - SendInput - (鼠标移动模拟)

ruby Dir.entries 不识别特殊字符

python - 是否可以找到或匹配两个具有不同特殊字符的名称django

c++ - 如何在没有现有引擎的情况下在游戏中设计我的 EventTrigger 框架?

linux - bash中有 "goto"语句吗?

linux - 如何在Linux机器上安装多个logstash实例?

linux - 在调试 perl 代码期间修改变量的值