【问题标题】:How do I use the L switch with a variable name?如何使用带有变量名的 L 开关?
【发布时间】:2021-02-16 20:44:25
【问题描述】:

我有这个代码:

#include <iostream>
#include <io.h>
#include <fcntl.h>
int main()
{

    _setmode(_fileno(stdout), _O_U16TEXT);

    std::string t_prefix = "\u2554";
    std::string t_middle = "";
    std::string t_suffix = "\u2557\n\u2551";
    int max_message_length = 33;

    for (int i = t_middle.length(); i < max_message_length; i++) {

        t_middle = "\u2550" + t_middle;

    }
    std::string complete_message = t_prefix + t_middle + t_suffix;


    std::wcout << L"\u2554" << t_middle.c_str() << L"\u2557\n\u2551";
    
    std::wcout << complete_message.c_str();
    //std::wcout << L"\u2554\n";

}

第一个 wout 行打印第一部分和最后一部分,中间部分打印出垃圾,因为它没有 L。 (如何将 L 与变量一起使用?) 第二个 wout 行结合了前缀、消息和后缀打印出垃圾,因为它需要 L 开关才能正确打印?我找到了一百万个关于如何使用直接硬编码文本 L"\u2554\u2550\u2550" 等的示例,但我希望程序更灵活一些,因此如果这样设置,游戏棋盘可以更宽。

【问题讨论】:

  • 您可以使用std::wstring(带有L"blah" 文字)代替std::string。我倾向于使用 UTF-8 无处不在的路线,但您的代码已经使用 _O_U16TEXT。否则,在输出字符串时,您需要将std::string 转换为std::wstring
  • 我需要知道如何将 L 与变量一起使用。如果我想在 "" 和 L variable_name 之间硬编码 33 个 Unicode 字符,则 L"blah" 工作正常会引发错误 unknow L
  • 你的意思是喜欢:std::wstring t_suffix = L"\u2557\n\u2551";
  • 不,我的意思是我需要知道如何在此语句中获取 L,这样它就不会抛出错误并正确打印出字符 std::wcout
  • 改成:std::wstring complete_message = t_prefix + t_middle + t_suffix;(另外三个变量也改成std::wstring),然后std::wcout &lt;&lt; complete_message;

标签: c++ unicode


【解决方案1】:

这似乎有效,并且至少可以为 Windows 做我需要它做的事情:

#include <io.h>
#include <fcntl.h>
#include <iostream>
#include <string>

int main()
{
   _setmode(_fileno(stdout), _O_U8TEXT);

   std::wstring t_prefix { L'\u2554' };
   std::wstring t_suffix { L"\u2557\n\u2551" };

   std::wstring t_middle;

   const size_t max_message_length { 33 };

   for (size_t i { t_middle.size() }; i < max_message_length; ++i)
   {
      t_middle += L'\u2550';
   }

   std::wstring complete_message { t_prefix + t_middle + t_suffix };

   std::wcout << complete_message << '\n';
}

这应该在 linux 上工作:

#include <iostream>

int main()
{
    std::string t_prefix = "╔";
    std::string t_middle;
    std::string t_suffix = "╗\n║";
    int max_message_length = 33;

    for (int i = t_middle.size(); i < max_message_length; ++i)
        t_middle = "═" + t_middle;

    std::string complete_message = t_prefix + t_middle + t_suffix;
    std::cout << complete_message << '\n';
}

【讨论】:

    猜你喜欢
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    相关资源
    最近更新 更多