Color console output with C++ in Windows

前端 未结 4 1169
面向向阳花
面向向阳花 2020-12-14 11:52

Is there a way to output colored text to the console? I am using Visual Studio 2010, and only need the code to work in Windows.

I have been unsuccessful in finding a

4条回答
  •  余生分开走
    2020-12-14 12:26

    Coloring C++ output in Windows is done through SetConsoleTextAttribute, where the HANDLE of the console passed in along with attributes. However, calling SetConsoleTextAttribute is cumbersome. Fortunately, there are lots of small libraries on the internet and github that can assist, you should just pick one with an API you like. If you want to change colors with operator<<, I recommend this header-only library https://github.com/ikalnitsky/termcolor. The api looks like this:

    using namespace termcolor;
    std::cout << grey    << "grey message"    << reset << std::endl;
    std::cout << red     << "red message"     << reset << std::endl;
    

    If having to reset the color turns you off, try my library. It's header-only too, Windows only, and it lets you color printf statements easily: https://github.com/jrebacz/colorwin. The api looks like this:

    using namepsace wincolor;
    std::cout << color(gray) << "grey message\n";
    std::cout << color(red) << "red message\n";
    
    std::cout << "normal color\n";
    {
        withcolor scoped(red);
        std::cout << "|red\n";
        std::cout << "|red again\n";
    }
    std::cout << "normal color\n";
    withcolor(cyan).printf("A cyan printf of %d\n", 1234);
    

提交回复
热议问题