将 wchar_t 转换为 wstring

时间:2021-03-14 08:58:46

标签: c++

我总是使用 wchar_t*wstring 转换为 std::wstring x(y)

但它在这段代码中不起作用:

        wchar_t f = ctoupper(*cp);
        std::wstring cc(f); 

cp 是一个 wchar_t*

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  

怎么了?

1 个答案:

答案 0 :(得分:2)

没有用于单个 wchar_t 值的 wstring 构造函数。您可以通过以下方式实现您的意图:

    std::wstring cc(1,f);   

您也可以直接从 c 风格的以空字符结尾的 wstring 数组中构造一个 wchar_t

    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; 

顺便说一下,您可以使用以下命令将完整的 wstring 转换为 upper:

    for (auto&x:cg) x=towupper(x);

(Online demo)

或者,您可能更喜欢 toupper(x,std::locale()) 以考虑当前语言环境中非 ascii 字符的转换规则。

相关问题