使用C++在控制台中着色文本

Sud*_*ha 72 c++ colorize colors

如何使用C++将彩色文本写入控制台?也就是说,如何用不同的颜色写出不同的文字?

She*_*een 95

在控制台文本中添加一点颜色

  HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
  // you can loop k higher to see more color choices
  for(int k = 1; k < 255; k++)
  {
    // pick the colorattribute k you want
    SetConsoleTextAttribute(hConsole, k);
    cout << k << " I want to be nice today!" << endl;
  }
Run Code Online (Sandbox Code Playgroud)

替代文字

字符属性 以下是如何解释"k"值.

  • 请注意,这只是Windows. (23认同)
  • @Misaki 我还没有测试过,但你能尝试删除 'endl' 位吗? (4认同)
  • 我需要包含哪些库才能了解 HANDLE 类? (3认同)
  • @STF 只使用 &lt;windows.h&gt; (3认同)
  • 如果我想在一行中添加多种颜色怎么办? (2认同)
  • 如何将其设置回默认值? (2认同)
  • @KiraSama 使用 GetConsoleScreenBufferInfo() API 获取 CONSOLE_SCREEN_BUFFER_INFO 的当前值,其成员 wAttributes 将具有当前的颜色信息。 (2认同)

use*_*312 17

标准C++没有"颜色"的概念.所以你要问的是取决于操作系统.

对于Windows,您可以查看SetConsoleTextAttribute函数.

在*nix上,您必须使用ANSI转义序列.

  • 请注意,ASNI序列(或至少其中一些)也适用于Windows的CMD.EXE. (2认同)
  • @Asu,他们没有在Win10周年纪念版之前.如果你的Win10我们是最新的,你就拥有它. (2认同)

Meh*_*our 11

ANSI转义颜色代码:

Name            BG  FG
Black           30  40
Red             31  41
Green           32  42
Yellow          33  43
Blue            34  44
Magenta         35  45
Cyan            36  46
White           37  47
Bright Black    90  100
Bright Red      91  101
Bright Green    92  102
Bright Yellow   93  103
Bright Blue     94  104
Bright Magenta  95  105
Bright Cyan     96  106
Bright White    97  107
Run Code Online (Sandbox Code Playgroud)

C / C ++的示例代码:

#include <iostream>
#include <string>

int main(int argc, char ** argv){

    printf("\n");
    printf("\x1B[31mTexting\033[0m\t\t");
    printf("\x1B[32mTexting\033[0m\t\t");
    printf("\x1B[33mTexting\033[0m\t\t");
    printf("\x1B[34mTexting\033[0m\t\t");
    printf("\x1B[35mTexting\033[0m\n");

    printf("\x1B[36mTexting\033[0m\t\t");
    printf("\x1B[36mTexting\033[0m\t\t");
    printf("\x1B[36mTexting\033[0m\t\t");
    printf("\x1B[37mTexting\033[0m\t\t");
    printf("\x1B[93mTexting\033[0m\n");

    printf("\033[3;42;30mTexting\033[0m\t\t");
    printf("\033[3;43;30mTexting\033[0m\t\t");
    printf("\033[3;44;30mTexting\033[0m\t\t");
    printf("\033[3;104;30mTexting\033[0m\t\t");
    printf("\033[3;100;30mTexting\033[0m\n");

    printf("\033[3;47;35mTexting\033[0m\t\t");
    printf("\033[2;47;35mTexting\033[0m\t\t");
    printf("\033[1;47;35mTexting\033[0m\t\t");
    printf("\t\t");
    printf("\n");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

GCC:

g++ cpp_interactive_terminal.cpp -o cpp_interactive_terminal.cgi
chmod +x cpp_interactive_terminal.cgi
./cpp_interactive_terminal.cgi
Run Code Online (Sandbox Code Playgroud)

  • @Mehdi Mohammadpour 我有 Windows 10,你的转义码*正在*为我工作,但在我看来,你已经颠倒了前景和背景代码。请把标题“FG”和“BG”颠倒好吗? (7认同)
  • Espace 序列基本上适用于 Linux。这通常不适用于 Windows (4认同)

小智 8

在 Windows 10 上,您可以通过以下方式使用转义序列:

#ifdef _WIN32
SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), ENABLE_VIRTUAL_TERMINAL_PROCESSING);
#endif
// print in red and restore colors default
std::cout << "\033[32m" << "Error!" << "\033[0m" << std::endl;
Run Code Online (Sandbox Code Playgroud)

  • @ProjectPhysX我找到了一个解决方案,我们应该先保存原来的控制台模式。``` DWORD dwMode; HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleMode(hOutput, &amp;dwMode); dwMode |= ENABLE_PROCESSED_OUTPUT | 启用虚拟终端处理;SetConsoleMode(hOutput, dwMode)); `` 这对我在 Win10 上有效。 (5认同)

Pro*_*ysX 8

这是我的轻量级解决方案,适用于 Windows 和 Linux:

#include <iostream>
#include <string>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
#include <Windows.h> // for displaying colors
#endif // Windows
using namespace std;

#define color_black      0
#define color_dark_blue  1
#define color_dark_green 2
#define color_light_blue 3
#define color_dark_red   4
#define color_magenta    5
#define color_orange     6
#define color_light_gray 7
#define color_gray       8
#define color_blue       9
#define color_green     10
#define color_cyan      11
#define color_red       12
#define color_pink      13
#define color_yellow    14
#define color_white     15

string get_textcolor_code(const int textcolor) { // Linux only
    switch(textcolor) {
        case  0: return "30"; // color_black      0
        case  1: return "34"; // color_dark_blue  1
        case  2: return "32"; // color_dark_green 2
        case  3: return "36"; // color_light_blue 3
        case  4: return "31"; // color_dark_red   4
        case  5: return "35"; // color_magenta    5
        case  6: return "33"; // color_orange     6
        case  7: return "37"; // color_light_gray 7
        case  8: return "90"; // color_gray       8
        case  9: return "94"; // color_blue       9
        case 10: return "92"; // color_green     10
        case 11: return "96"; // color_cyan      11
        case 12: return "91"; // color_red       12
        case 13: return "95"; // color_pink      13
        case 14: return "93"; // color_yellow    14
        case 15: return "97"; // color_white     15
        default: return "37";
    }
}
string get_backgroundcolor_code(const int backgroundcolor) { // Linux only
    switch(backgroundcolor) {
        case  0: return  "40"; // color_black      0
        case  1: return  "44"; // color_dark_blue  1
        case  2: return  "42"; // color_dark_green 2
        case  3: return  "46"; // color_light_blue 3
        case  4: return  "41"; // color_dark_red   4
        case  5: return  "45"; // color_magenta    5
        case  6: return  "43"; // color_orange     6
        case  7: return  "47"; // color_light_gray 7
        case  8: return "100"; // color_gray       8
        case  9: return "104"; // color_blue       9
        case 10: return "102"; // color_green     10
        case 11: return "106"; // color_cyan      11
        case 12: return "101"; // color_red       12
        case 13: return "105"; // color_pink      13
        case 14: return "103"; // color_yellow    14
        case 15: return "107"; // color_white     15
        default: return  "40";
    }
}
string get_print_color(const int textcolor) { // Linux only
    return "\033["+get_textcolor_code(textcolor)+"m";
}
string get_print_color(const int textcolor, const int backgroundcolor) { // Linux only
    return "\033["+get_textcolor_code(textcolor)+";"+get_backgroundcolor_code(backgroundcolor)+"m";
}
void print_color(const int textcolor) {
#if defined(_WIN32)
    static const HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(handle, textcolor);
#elif defined(__linux__)
    cout << get_print_color(textcolor);
#endif // Windows/Linux
}
void print_color(const int textcolor, const int backgroundcolor) {
#if defined(_WIN32)
    static const HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(handle, backgroundcolor<<4|textcolor);
#elif defined(__linux__)
    cout << get_print_color(textcolor, backgroundcolor);
#endif // Windows/Linux
}
void print_color_reset() {
#if defined(_WIN32)
    static const HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(handle, 7); // reset color
#elif defined(__linux__)
    cout << "\033[0m"; // reset color
#endif // Windows/Linux
}

void println(const string& s="") {
    cout << s << endl;
}
void print(const string& s="") {
    cout << s;
}
void print(const string& s, const int textcolor) {
    print_color(textcolor);
    cout << s;
    print_color_reset();
}
void print(const string& s, const int textcolor, const int backgroundcolor) {
    print_color(textcolor, backgroundcolor);
    cout << s;
    print_color_reset();
}
void print_no_reset(const string& s, const int textcolor) { // print with color, but don't reset color afterwards (faster)
    print_color(textcolor);
    cout << s;
}
void print_no_reset(const string& s, const int textcolor, const int backgroundcolor) { // print with color, but don't reset color afterwards (faster)
    print_color(textcolor, backgroundcolor);
    cout << s;
}
Run Code Online (Sandbox Code Playgroud)

这是如何使用它的示例:

int main() {
    print("Hello ", color_red, color_blue);
    print("World!\n", color_black, color_yellow);
    println();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Der*_*rzu 7

您可以使用 ANSI 转义序列对控制台文本进行着色,它适用于 Windows 和 Linux。对于Windows,您需要激活虚拟终端。

#include <iostream>

#ifdef _WIN32
#include <windows.h>

#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#define DISABLE_NEWLINE_AUTO_RETURN  0x0008

void activateVirtualTerminal()
{       
    HANDLE handleOut = GetStdHandle(STD_OUTPUT_HANDLE);
    DWORD consoleMode;
    GetConsoleMode( handleOut , &consoleMode);
    consoleMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
    consoleMode |= DISABLE_NEWLINE_AUTO_RETURN;            
    SetConsoleMode( handleOut , consoleMode );
}
#endif

using namespace std;

enum COLORS {
    NC=-1,
    BLACK,
    RED,
    GREEN,
    YELLOW,
    BLUE,
    MAGENTA,
    CYAN,
    WHITE,
};

/**
* Colorize terminal colors ANSI escape sequences.
*
* @param font font color (-1 to 7), see COLORS enum
* @param back background color (-1 to 7), see COLORS enum
* @param style font style (1==bold, 4==underline)
**/
const char *colorize(int font, int back = -1, int style = -1) {
    static char code[20];
    
    if (font >= 0)
        font += 30;
    else
        font = 0;
    if (back >= 0)
        back += 40;
    else
        back = 0;

    if (back > 0 && style > 0) {
        sprintf(code, "\033[%d;%d;%dm", font, back, style);
    } else if (back > 0) {
        sprintf(code, "\033[%d;%dm", font, back);
    } else {

        sprintf(code, "\033[%dm", font);
    }

    return code;
}


int main()
{
#ifdef _WIN32
    activateVirtualTerminal();
#endif

    cout << colorize(RED) << "trying red" << colorize(NC) << endl;
    cout << colorize(RED, BLACK) << "red and black background" << colorize(NC) << endl;
    cout << colorize(YELLOW, BLUE, 1) << "yellow blue bold" << colorize(NC) << endl;
    cout << colorize(BLACK, WHITE) << "Black white" << colorize(NC) << endl;
    cout << colorize(MAGENTA, CYAN) << "Magenta cyan" << colorize(NC) << endl;

    return 1;
}
Run Code Online (Sandbox Code Playgroud)


Che*_*Alf 5

假设您在谈论Windows控制台窗口,请在MSDN Library文档中查找控制台功能。

否则,或更一般而言,它取决于控制台。C ++库不支持颜色。但是用于控制台处理的库可能/将支持颜色。例如,谷歌“ ncurses颜色”。

对于连接的串行终端和终端仿真器,您可以通过输出“转义序列”来控制事情。这些通常以ASCII 27(ASCII中的转义字符)开头。有一个ANSI标准和许多自定义方案。


Sud*_*ha 5

您可以编写方法并像这样调用


HANDLE  hConsole;
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
int col=12;

// color your text in Windows console mode
// colors are 0=black 1=blue 2=green and so on to 15=white  
// colorattribute = foreground + background * 16
// to get red text on yellow use 4 + 14*16 = 228
// light red on yellow would be 12 + 14*16 = 236

FlushConsoleInputBuffer(hConsole);
SetConsoleTextAttribute(hConsole, col);

cout << "Color Text";

SetConsoleTextAttribute(hConsole, 15); //set back to black background and white text
Run Code Online (Sandbox Code Playgroud)

  • 请注意,“SetConsoleTextAttribute(hConsole, 15);”将颜色设置为*亮白色*,而不是*白色*。***7 - 白色。*** 和 ***15 - 亮白色*** (2认同)

Inc*_*nnu 5

你可以做的最简单的方法是:

#include <stdlib.h>

system("Color F3");
Run Code Online (Sandbox Code Playgroud)

其中“F”是背景颜色的代码,3 是文本颜色的代码。

弄乱它以查看其他颜色组合:

system("Color 1A");
std::cout << "Hello, what is your name?" << std::endl;
system("Color 3B");
std::cout << "Hello, what is your name?" << std::endl;
system("Color 4c");
std::cout << "Hello, what is your name?" << std::endl;
Run Code Online (Sandbox Code Playgroud)

注意:我只在 Windows 上测试过。作品。正如所指出的,这不是跨平台的,它不适用于 Linux 系统。

  • 这是一个糟糕的做法!代码不跨平台,在Linux系统下无法运行 (5认同)

baz*_*rek 5

我发现仅标头的开源 C++ 库可在多个平台上运行:https : //github.com/imfl/color-console

颜色控制台:

一个轻量级的仅标头 C++ 库,通过一个非常易于使用的 API 为您的 Windows 控制台带来颜色,让您免于每次拨打电话时设置和重置屏幕颜色的负担。

在此处输入图片说明

#include "../include/color.hpp"
#include <iostream>

int main() {
    std::cout << dye::aqua("Hello, World!") << std::endl;
    return 0; } 
Run Code Online (Sandbox Code Playgroud)

你正在看到你好,世界!在水中。
在此处输入图片说明

为什么使用它? 在此处输入图片说明

无需重置:市场上的大多数解决方案都像操纵器一样工作,它不断要求您在设置后重置屏幕颜色。虽然这个库中的 Hue 命名空间中也提供了这种传统方法......

制表:

如果您不仅要更改颜色,而且要以更易读的形式(例如表格形式)打印文本,也可以使用https://github.com/p-ranav/tabulate来更改颜色并在控制台中绘制表格。

tabulate 是一个只有头文件的库。只需将 include/ 添加到您的 include_directories 中,您就可以开始使用了。single_include/ 中还提供了单个头文件版本。注意制表支持 >=C++11。 在此处输入图片说明

  • 这些都非常好。多谢。但不好的是第一个仅是 Windows 特定的。 (2认同)
  • 过去两天我发现了更好的多平台颜色库:https://github.com/jupyter-xeus/cpp-terminal 它是由来自 CERN 的 Jupyter-xeus 开发的。 (2认同)