【问题标题】:Converting wchar_t to wstring将 wchar_t 转换为 wstring
【发布时间】:2021-03-14 08:58:46
【问题描述】:

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

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

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

cpwchar_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  

怎么了?

【问题讨论】:

  • 你知道你得到的是第一个字符,而不是整个字符串吗?
  • basic_stringstringwstring 下的模板)因其大量的成员函数而令人讨厌。尽管如此,还是值得看看它们以获得一个概览。以cppreference.com 为例。

标签: c++


【解决方案1】:

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

    std::wstring cc(1,f);   

您也可以直接从 c 风格的空终止 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; 

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

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

(Online demo)

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

【讨论】:

  • 谢谢,您知道如何将 wstring 转换为大写吗?
  • stackoverflow.com/… -- 请将问题集中在一个主题上。要求澄清是可以的,但不要将独立问题作为现有问题的附加问题。
  • @Frank 我用更多解释编辑了我的答案
  • 谢谢 Christophe 会帮上大忙的! :)
猜你喜欢
  • 2017-12-12
  • 2013-07-28
  • 2012-02-13
  • 2015-09-16
  • 1970-01-01
  • 2011-07-29
  • 2013-02-02
  • 2015-02-05
  • 1970-01-01
相关资源
最近更新 更多