Print Coloured Text to Console in C++

前端 未结 4 1466
眼角桃花
眼角桃花 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:15

    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 
    #include 
    #include 
    
    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 &operator<<(basic_ostream &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();
    }
    

提交回复
热议问题