[英]Converting wchar_t to wstring
I always convert wchar_t*
to wstring
with std::wstring x(y)
我总是使用
std::wstring x(y)
将wchar_t*
转换为wstring
But it is not working in this code:但它不适用于此代码:
wchar_t f = ctoupper(*cp);
std::wstring cc(f);
cp
is a wchar_t*
cp
是wchar_t*
Error in the std::wstring cc(f)
line: std::wstring cc(f)
行中的错误:
E0289 no instance of constructor "std::basic_string<_Elem, _Traits, _Alloc>::basic_string [with _Elem=wchar_t, _Traits=std::char_traits<wchar_t>, _Alloc=std::allocator<wchar_t>]" matches the argument list
Whats wrong?怎么了?
There is no wstring
constructor for a single wchar_t
value.单个
wchar_t
值没有wstring
构造函数。 You can achieve your intent with the following:您可以通过以下方式实现您的意图:
std::wstring cc(1,f);
You can also directly construct a wstring
out of a c-style null-terminated wchar_t
array:您还可以直接从 c 样式的以 null 结尾的
wchar_t
数组构造wstring
:
std::wstring cc(1,f); // wstring made with a wchar_t f repeated 1 time
std::wstring cg(cp); // wstring made with a wchart_t null terminated array
std::wcout<<cc<<std::endl<<cg<<std::endl;
By the way, you can convert the full wstring to upper with:顺便说一句,您可以使用以下命令将完整的 wstring 转换为大写:
for (auto&x:cg) x=towupper(x);
( Online demo ) (在线演示)
Alternatively you may prefer toupper(x,std::locale())
toa take into account conversion rules for non ascii characters in your current locale.或者,您可能更喜欢
toupper(x,std::locale())
考虑到当前语言环境中非 ascii 字符的转换规则。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.