Print Coloured Text to Console in C++

前端 未结 4 1478
眼角桃花
眼角桃花 2020-12-31 21:38

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

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

Cons         


        
4条回答
  •  梦谈多话
    2020-12-31 22:24

    I did a search for "c++ console write colored text" and came up with this page at 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):

    #include 
    #include 
    #include 
    
    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

提交回复
热议问题