在 C++ 中将彩色文本打印到控制台

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/899341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:50:52  来源:igfitidea点击:

Print Coloured Text to Console in C++

c++programming-languagestextconsoleterminal

提问by Brock Woolf

I would like to write a Console class that can output coloured text to the console.

我想编写一个可以将彩色文本输出到控制台的 Console 类。

So I can do something like (basically a wrapper for printf):

所以我可以做一些类似的事情(基本上是 printf 的包装器):

Console::Print( "This is a non-coloured message\n" );
Console::Warning( "This is a YELLOW warning message\n" );
Console::Error( "This is a RED error message\n" );

How would I print different coloured text to the Windows Console?

如何将不同颜色的文本打印到 Windows 控制台?

回答by Skurmedel

Check out this guide. I would make a custom manipulator so I could do something like:

查看本指南。我会制作一个自定义操纵器,以便我可以执行以下操作:

std::cout << "standard text" << setcolour(red) << "red text" << std::endl;

Here's a small guide on how to implement your own manipulator.

是有关如何实现自己的操纵器的小指南。

A quick code example:

一个快速的代码示例:

#include <iostream>
#include <windows.h>
#include <iomanip>

using namespace std;

enum colour { DARKBLUE = 1, DARKGREEN, DARKTEAL, DARKRED, DARKPINK, DARKYELLOW, GRAY, DARKGRAY, BLUE, GREEN, TEAL, RED, PINK, YELLOW, WHITE };

struct setcolour
{
   colour _c;
   HANDLE _console_handle;


       setcolour(colour c, HANDLE console_handle)
           : _c(c), _console_handle(0)
       { 
           _console_handle = console_handle;
       }
};

// We could use a template here, making it more generic. Wide streams won't
// work with this version.
basic_ostream<char> &operator<<(basic_ostream<char> &s, const setcolour &ref)
{
    SetConsoleTextAttribute(ref._console_handle, ref._c);
    return s;
}

int main(int argc, char *argv[])
{
    HANDLE chandle = GetStdHandle(STD_OUTPUT_HANDLE);
    cout << "standard text" << setcolour(RED, chandle) << " red text" << endl;

    cin.get();
}

回答by ChrisF

I did a search for "c++ console write colored text" and came up with this pageat about 4 or 5. As the site has a copy & paste section I thought I'd post it here (another question on link rot also prompted this):

我搜索了“c++ 控制台写彩色文本”,并在大约 4 或 5时找到了这个页面。由于该站点有一个复制和粘贴部分,我想我会在这里发布它(另一个关于链接腐烂的问题也提示了这个):

#include <stdlib.h>
#include <windows.h>
#include <iostream>

using namespace std;

enum Color { DBLUE=1,GREEN,GREY,DRED,DPURP,BROWN,LGREY,DGREY,BLUE,LIMEG,TEAL,
    RED,PURPLE,YELLOW,WHITE,B_B };
/* These are the first 16 colors anyways. You test the other hundreds yourself.
   After 15 they are all combos of different color text/backgrounds. */

bool quit;

void col(unsigned short color)
{
    HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hcon,color);
}

istream &operator>> ( istream &in, Color &c )
{
    int tint;
    cin >> tint;
    if (tint==-1) quit=true;
    c=(Color)tint;
}

int main()
{
    do {
        col(7); // Defaults color for each round.
        cout << "Enter a color code, or -1 to quit... ";
        Color y;
        cin >> y; // Notice that >> is defined above for Color types.
        col(y); // Sets output color to y.
        if (!quit) cout << "Color: " << (int)y << endl;
    } while (!quit);
    return 0;
}

For C# there's this page

对于 C# 有这个页面

回答by madhudskumar

#include <windows.h>
#include <iostream.h>
using namespace std;

int main()
{
    HANDLE hOut;

    hOut = GetStdHandle(STD_OUTPUT_HANDLE);

    SetConsoleTextAttribute(hOut,
                            BACKGROUND_RED);
    cout << "Red     " << flush;
    SetConsoleTextAttribute(hOut,
                            BACKGROUND_RED |
                            BACKGROUND_INTENSITY);
    cout << "Red     " << endl;

    SetConsoleTextAttribute(hOut,
                            BACKGROUND_GREEN);
    cout << "Green   " << flush;
    SetConsoleTextAttribute(hOut,
                            BACKGROUND_GREEN |
                            BACKGROUND_INTENSITY);
    cout << "Green   " << endl;

    SetConsoleTextAttribute(hOut,
                            BACKGROUND_BLUE);
    cout << "Blue    " << flush;
    SetConsoleTextAttribute(hOut,
                            BACKGROUND_BLUE |
                            BACKGROUND_INTENSITY);
    cout << "Blue    " << endl;

    SetConsoleTextAttribute(hOut,
                            BACKGROUND_RED | 
                            BACKGROUND_GREEN);
    cout << "Yellow  " << flush;
    SetConsoleTextAttribute(hOut,
                            BACKGROUND_RED | 
                            BACKGROUND_GREEN |
                            BACKGROUND_INTENSITY);
    cout << "Yellow  " << endl;

    SetConsoleTextAttribute(hOut,
                            BACKGROUND_GREEN | 
                            BACKGROUND_BLUE);
    cout << "Cyan    " << flush;
    SetConsoleTextAttribute(hOut,
                            BACKGROUND_GREEN | 
                            BACKGROUND_BLUE |
                            BACKGROUND_INTENSITY);
    cout << "Cyan    " << endl;

    SetConsoleTextAttribute(hOut,
                            BACKGROUND_BLUE | 
                            BACKGROUND_RED);
    cout << "Magenta " << flush;
    SetConsoleTextAttribute(hOut,
                            BACKGROUND_BLUE | 
                            BACKGROUND_RED |
                            BACKGROUND_INTENSITY);
    cout << "Magenta " << endl;

    SetConsoleTextAttribute(hOut,
                            BACKGROUND_RED | 
                            BACKGROUND_GREEN | 
                            BACKGROUND_BLUE);
    cout << "White   " << flush;
    SetConsoleTextAttribute(hOut,
                            BACKGROUND_RED | 
                            BACKGROUND_GREEN | 
                            BACKGROUND_BLUE |
                            BACKGROUND_INTENSITY);
    cout << "White   " << endl;

    return 0;
}

回答by Shanaka Rusith

use these functions

使用这些功能

enum c_color{BLACK=30,RED=31,GREEN=32,YELLOW=33,BLUE=34,MAGENTA=35,CYAN=36,WHITE=37};
enum c_decoration{NORMAL=0,BOLD=1,FAINT=2,ITALIC=3,UNDERLINE=4,RIVERCED=26,FRAMED=51};
void pr(const string str,c_color color,c_decoration decoration=c_decoration::NORMAL){
  cout<<"3["<<decoration<<";"<<color<<"m"<<str<<"3[0m";
}

void prl(const string str,c_color color,c_decoration decoration=c_decoration::NORMAL){
   cout<<"3["<<decoration<<";"<<color<<"m"<<str<<"3[0m"<<endl;
}