将窄字符串转换为宽字符串

sap*_*Pro 6 c++ string unicode visual-c++

我怎样才能将窄幅转换string为宽幅string

我试过这个方法:

string myName;
getline( cin , myName );
wstring printerName( L(myName) );  // error C3861: 'L': identifier not found
wchar_t* WprinterName = printerName.c_str(); // error C2440: 'initializing' : cannot convert from 'const wchar_t *' to 'wchar_t *'
Run Code Online (Sandbox Code Playgroud)

但我得到上面列出的错误.

为什么我会收到这些错误?我该如何解决它们?

有没有其他方法可以直接将narrow字符串转换为wide字符串?

Chr*_*her 7

你应该做这个 :

inline std::wstring convert( const std::string& as )
{
            // deal with trivial case of empty string
    if( as.empty() )    return std::wstring();

            // determine required length of new string
    size_t reqLength = ::MultiByteToWideChar( CP_UTF8, 0, as.c_str(), (int)as.length(), 0, 0 );

            // construct new string of required length
    std::wstring ret( reqLength, L'\0' );

            // convert old string to new string
    ::MultiByteToWideChar( CP_UTF8, 0, as.c_str(), (int)as.length(), &ret[0], (int)ret.length() );

            // return new string ( compiler should optimize this away )
    return ret;
}
Run Code Online (Sandbox Code Playgroud)

CP_UTF8当你有另一个编码替换代码页时,这需要std :: string为UTF-8().

另一种方式可能是:

inline std::wstring convert( const std::string& as )
{
    wchar_t* buf = new wchar_t[as.size() * 2 + 2];
    swprintf( buf, L"%S", as.c_str() );
    std::wstring rval = buf;
    delete[] buf;
    return rval;
}
Run Code Online (Sandbox Code Playgroud)


Bla*_*zes 6

如果源是ASCII编码的,则可以执行以下操作:

wstring printerName;
printerName.assign( myName.begin(), myName.end() );
Run Code Online (Sandbox Code Playgroud)

  • *“我很惊讶这没有更多的赞成票。”*我猜是因为它在(可能)最常见的情况下失败,即如果“myName”是UTF-8。 (2认同)