Отпечатайте цветен текст в конзолата в C++

Бих искал да напиша клас Console, който може да извежда цветен текст към конзолата.

Така че мога да направя нещо като (основно обвивка за 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" );

Как да отпечатам различен цветен текст в конзолата на Windows?


person Brock Woolf    schedule 22.05.2009    source източник


Отговори (3)


Вижте това ръководство. Бих направил персонализиран манипулатор, за да мога да направя нещо като:

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

Ето малко ръководство за това как да внедрите свой собствен манипулатор.

Пример за бърз код:

#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();
}
person Skurmedel    schedule 22.05.2009
comment
Този код всъщност не работи, но предишната ви версия, която току-що заменихте, работи. Все пак ще проверя отново дали го правя - person Brock Woolf; 22.05.2009
comment
@Brock Woolf: Да, съжалявам. Имах проблем с копирането на ДРЪЖКАТА. - person Skurmedel; 22.05.2009
comment
Ако искате да промените цветовете по средата на линията, уверете се, че сте изпратили std::flush, преди да извикате отново setcolour(). - person jep; 20.06.2015

Направих търсене за „c++ console write colored text“ и попаднах на тази страница на около 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;
}

За C# има тази страница

person ChrisF    schedule 22.05.2009
comment
Тази първа връзка, която имахте, беше информативна, въпреки че беше C#. - person sean e; 22.05.2009
comment
Терминът за търсене беше c# console.write цветен текст в този случай - person ChrisF; 22.05.2009

използвайте тези функции

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<<"\033["<<decoration<<";"<<color<<"m"<<str<<"\033[0m";
}

void prl(const string str,c_color color,c_decoration decoration=c_decoration::NORMAL){
   cout<<"\033["<<decoration<<";"<<color<<"m"<<str<<"\033[0m"<<endl;
}
person Shanaka Rusith    schedule 24.04.2016