C++ 不能将字符串转换为 wstring [英] c++ can't convert string to wstring

查看:30
本文介绍了C++ 不能将字符串转换为 wstring的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to convert a string variable to wstring due to some german characters that cause problem when doing a substr over the variable. The start position is falsified when any these special characters is present before it. (For instance: for "ä" size() returns 2 instead of 1)

我知道以下转换有效:

wstring ws = L"ä";

既然我正在尝试转换一个变量,我想知道是否有替代方法,例如

Since, I am trying to convert a variable, I would like to know if there is an alternative way for it such as

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

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

Beside that, I have already tried the following example to convert string to 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 编译的.感谢您的帮助!

I am using ubuntu 14.04 and my main.cpp is compiled with cmake. Thanks for your help!

推荐答案

hahakubile"的解决方案对我有用:

The solution from "hahakubile" worked for me:

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% 正确:

But the return value is not 100% correct:

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

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

I am wondering why it replaced german characters with symbols.

再次感谢!

这篇关于C++ 不能将字符串转换为 wstring的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆