将窄字符串转换为宽字符串 [英] converting narrow string to wide string
本文介绍了将窄字符串转换为宽字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将窄的字符串
转换为宽的字符串
?
How can i convert a narrow string
to a wide 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 *'
但是我得到上面列出的错误。
But i get errors as listed above.
为什么我得到这些错误?我如何解决他们?
Why do i get these errors ? How can i fix them ?
是否有其他方法直接将 string
字符串转换为 code> string?
Is there any other method of directly converting a narrow
string to a wide
string ?
推荐答案
您应该这样做:
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;
}
这期望std :: string为UTF-8
This expects the std::string to be UTF-8 (CP_UTF8
), when you have another encoding replace the codepage.
另一种方法可以是:
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;
}
这篇关于将窄字符串转换为宽字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文