在C ++中打印彩色文本到控制台 [英] Print Coloured Text to Console in C++

查看:159
本文介绍了在C ++中打印彩色文本到控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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

/ p>

  Console :: Print(This is an non-colored message\ n); 
Console :: Warning(This is a YELLOW warning message\\\
);
Console :: Error(这是一个RED错误消息\\\
);

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

解决方案

查看本指南。我会做一个自定义的操纵器,所以我可以做一些像:

  std :: cout< 标准文本<< setcolour(红色)<< 红色文本<< std :: endl; 

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



示例:

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

using namespace std;

枚举color {DARKBLUE = 1,DARKGREEN,DARKTEAL,DARKRED,DARKPINK,DARKYELLOW,GREY,DARKGRAY,BLUE,GREEN,TEAL,RED,PINK,YELLOW,WHITE}

struct setcolour
{
color _c;
HANDLE _console_handle


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

//我们可以在这里使用一个模板,使其更通用。宽流不会
//使用此版本。
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<< 标准文本<< setcolour(RED,chandle)<< 红色文本<< endl;

cin.get();
}


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):

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?

解决方案

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();
}

这篇关于在C ++中打印彩色文本到控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆