【问题标题】:How to use operator L on array? (C++, Visual Studio 2019)如何在数组上使用运算符 L? (C++,Visual Studio 2019)
【发布时间】:2020-03-01 10:17:54
【问题描述】:

第 2 部分介绍 C++ 中的字符编码(作者 User123)。

<- Go to the previous post.

我昨天正在编写一些代码,this question 中的Paul Sanders 告诉我有用的解决方案:他告诉我不要使用std::cout &lt;&lt; "something";,而是使用std::wcout &lt;&lt; L"something";

但我还有另一个问题。现在我想做这样的事情(一些特殊字符,但在数组中):

#include <iostream>
using namespace std;
string myArray[2] = { "łŁšđřžőšě", "×÷¤ßł§ř~ú" };
int main()
{
    cout << myArray[0] << endl << myArray[1];
    return 0;
}

但现在我得到了一些非常不寻常的东西:

│úÜ­°×§Üý
θĄ▀│ž°~˙

如果我在数组前面添加L,我会得到(Visual Studio 2019):

C++ initialization with '{...}' expected for aggregate object

如何在数组中表示这些特殊字符?

【问题讨论】:

    标签: c++ encoding utf-8 visual-studio-2019


    【解决方案1】:
    #include <iostream>
    using namespace std;
    wstring myArray[2] = { L"łŁšđřžőšě", L"×÷¤ßł§ř~ú" };
    int main()
    {
        wcout << myArray[0] << endl << myArray[1];
        return 0;
    }
    

    L 只能直接应用于字符串文字。结果是wchar_t[]字符)类型的字符串文字,而不是通常的char_t[]字符),因此您不能将其保存在@987654325 @。您需要将其保存在wstring 中。要输出wstring,您需要将其传递给wcout,而不是cout

    【讨论】:

    • 不适用于 Visual Studio 2019、Windows 7 专业版。根本没有任何字符,只是空白输出。
    • @User123 但你是说std::wcout &lt;&lt; L"łŁšđřžőšě"; 或类似的东西有效?
    • 是的,但我需要指定#include &lt;fcntl.h&gt;#include &lt;io.h&gt;,然后指定_setmode(_fileno(stdout), _O_U16TEXT);
    • @User123 然后对这个例子做同样的事情,它应该可以工作。宽字符的行为细节由实现定义。
    • @User123 使用wcin 而不是cin
    猜你喜欢
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 2020-04-02
    • 1970-01-01
    相关资源
    最近更新 更多