C++实现控制台输出具有颜色类

直接贴代码:.h文件
#pragma once
#include "config.h"

#define BLACK	0
#define GREEN	2
#define RED		4
#define YELLOW	8

#ifdef WIN32 
#include<windows.h>
#endif // WIN32 

class CLog
{
public:
	~CLog();
	static void must(const char* msg);
	static void must(std::string msg);

	static void warn(const char* msg);
	static void warn(std::string msg);

	static void error(const char* msg);
	static void error(std::string msg);

protected:
	static inline void setConsoleColor(int level)
	{
#ifdef WIN32
		(level&m_curColor) || (m_curColor = level, SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), m_curColor | FOREGROUND_INTENSITY));
#endif
	}
private:
	CLog();
	static int m_curColor;
};


cpp文件

#include "log.h"
int CLog::m_curColor = BLACK;

CLog::CLog()
{
	
}

CLog::~CLog()
{

}

void CLog::must(const char* msg)
{
	setConsoleColor(GREEN);
	std::cout << msg << std::endl;
}

void CLog::must(std::string msg)
{
	must(msg.c_str());
}

void CLog::warn(const char* msg)
{
	setConsoleColor(YELLOW);
	std::cout << msg << std::endl;
}

void CLog::warn(std::string msg)
{
	warn(msg.c_str());
}

void CLog::error(const char* msg)
{
	setConsoleColor(RED);
	std::cout << msg << std::endl;
}

void CLog::error(std::string msg)
{
	error(msg.c_str());
}

main调用

#include"log.h"
int main()
{

	CLog::warn("please attention this is warn");
	CLog::warn("please attention this is warn");
	CLog::must("please attention this is must");
	CLog::error("please attention this is error");
	getchar();
	return 0;

}

因为我使用了(level&m_curColor) 这个来设置颜色值 所以有些颜色不能使用,如果你有需要你可以重新改变下我的设置方式,具体颜色值如下

0=黑色
1=蓝色
2=绿色
3=湖蓝色
4=红色
5=紫色
6=黄色
7=白色
8=灰色
9=淡蓝色
A=淡绿色
B=淡浅绿色
C=淡红色
D=淡紫色
E=淡黄色
F=亮白色

其中FOREGROUND_INTENSITY代表前景高亮,config.h头文件内容如下

#define WIN32
#include <string>
#include <iostream>

如你有更好办法,请指教。

这个 颜色设置主要是在开发项目时候经常使用到的。里面还有要添加写日志到文件中的功能还没写......

未完待续。。。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值