BASH下程序运行的彩色输出

10

我需要让终端上的某些文本更加显眼,我的想法是给文本着色。可以选择实际文本或每个字母矩形内的空格(类似于vi的光标)。 我认为对于我的应用程序而言,唯一两个重要的额外规格是:程序应该与发行版无关(但代码一定会在BASH下运行),并且在写入文件时不应输出额外字符(无论是来自实际代码还是通过输出管道)。

我在网上搜索了一些信息,但我只能找到有关已弃用的cstdlib(stdlib.h)的信息,我需要(实际上更多是“想要”)使用iostream的功能来完成它。

5个回答

14

大多数终端支持ASCII颜色序列。它们通过输出ESC,后跟[,然后是一个以分号分隔的颜色值列表,然后是m来工作。这些是常见的值:

Special
0  Reset all attributes
1  Bright
2  Dim
4  Underscore   
5  Blink
7  Reverse
8  Hidden

Foreground colors
30  Black
31  Red
32  Green
33  Yellow
34  Blue
35  Magenta
36  Cyan
37  White

Background colors
40  Black
41  Red
42  Green
43  Yellow
44  Blue
45  Magenta
46  Cyan
47  White

因此,输出"\033[31;47m"应该使终端前景(文本)颜色为红色,背景颜色为白色。

你可以在C++中将其包装得很好:

enum Color {
    NONE = 0,
    BLACK, RED, GREEN,
    YELLOW, BLUE, MAGENTA,
    CYAN, WHITE
}

std::string set_color(Color foreground = 0, Color background = 0) {
    char num_s[3];
    std::string s = "\033[";

    if (!foreground && ! background) s += "0"; // reset colors if no params

    if (foreground) {
        itoa(29 + foreground, num_s, 10);
        s += num_s;

        if (background) s += ";";
    }

    if (background) {
        itoa(39 + background, num_s, 10);
        s += num_s;
    }

    return s + "m";
}

1
不要忘记序列的终止符“'m'”,例如“\033]31;47m”。 - Some programmer dude

4
这是@nightcracker的代码版本,使用stringstream代替itoa。(在clang++、C++11、OS X 10.7、iTerm2和bash上运行)
#include <iostream>
#include <string>
#include <sstream>

enum Color
{
    NONE = 0,
    BLACK, RED, GREEN,
    YELLOW, BLUE, MAGENTA,
    CYAN, WHITE
};

static std::string set_color(Color foreground = NONE, Color background = NONE)
{
    std::stringstream s;
    s << "\033[";
    if (!foreground && ! background){
        s << "0"; // reset colors if no params
    }
    if (foreground) {
        s << 29 + foreground;
        if (background) s << ";";
    }
    if (background) {
        s << 39 + background;
    }
    s << "m";
    return s.str();
}

int main(int agrc, char* argv[])
{
    std::cout << "These words should be colored [ " <<
        set_color(RED) << "red " <<
        set_color(GREEN) << "green " <<
        set_color(BLUE) << "blue" <<
        set_color() <<  " ]" << 
        std::endl;
    return EXIT_SUCCESS;
}

2

0

您可以从Github(https://github.com/Spezialcoder/libcolor)使用libcolor。

#include "libcolor/libcolor.h"
#include <iostream>
using namespace std; 
int main()
{
     cout << font_color::green << "Hello World" << endl;
}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接