【问题标题】:C++ Changing Text ColorC++ 更改文本颜色
【发布时间】:2020-12-19 05:00:41
【问题描述】:

我正在尝试更改 C++ 中文本的颜色,我能找到的唯一答案是 C 而不是 C++。我曾尝试使用 conio.h 但不明白如何使用它。有人可以帮忙吗?

【问题讨论】:

  • 这能回答你的问题吗? How to change text and background color?
  • C++ 没有“文本颜色”的概念,因此这在可移植的方式中是不可能的。对于特定于平台的解决方案,请参阅例如Colorizing text in the console with C++
  • 您不能使用 conio.h,它是特定于平台的。但是在像 Borland 这样的编译器中,你可以找到 textColor() 但你不能承认它一直都在这里
  • C++ 标准中没有定义conio.h。不要使用不可移植的非标准头文件(尤其是那些来自 DOS 时代的 :)
  • 这能回答你的问题吗? Colorizing text in the console with C++

标签: c++ conio


【解决方案1】:

文本着色并不是真正的 C++ 方面。在某些 unix 终端中,您可以直接在程序中使用 \e[0;31m message \e[0m 之类的代码(尽管您可能希望创建一个 API 以方便使用)。但是,这在 Windows 控制台中不起作用。这取决于所使用的操作系统和终端。

【讨论】:

    【解决方案2】:

    如果你不需要坚持非跨平台库conio.h。我建议使用跨平台解决方案:仅标头,moderc C++ rang 库。我在我的大部分项目中都使用它,它真的很容易使用

    【讨论】:

      【解决方案3】:

      我发现了如何使用 windows.h 更改文本的颜色。这是我使用的代码示例(复制自https://cboard.cprogramming.com/)。

      #include <iostream>
      #include <windows.h>
      
      using namespace std;
      
      int main()
      {
          HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);                                  // h is your link to the console
          SetConsoleTextAttribute(h, 1);    cout << "Sentence in blue" << '\n';        // 1 happens to be blue
          SetConsoleTextAttribute(h, 2);    cout << "Sentence in green" << '\n';       // 2 is green
          SetConsoleTextAttribute(h, 4);    cout << "Sentence in red" << '\n';         // 4 is red
          SetConsoleTextAttribute(h, 7);    cout << "Sentence in white" << '\n';       // etc.
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-06
        • 2015-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多