std::cout彩色输出

mac
Mac OS效果

Windows
Windows 效果

想写这个东西其实是因为最近要写个命令行的工具,但是有个问题是什么呢?就是传统的那个黑漆漆的窗口看起来很蛋疼。并且完全看不到重点,于是就想起来这么一个东西。相对来说针对*nix的系统方法会比较通用一些,而windows下这个东西需要用到专门的Windows相关的api来实现。

下面先说通用的方法:

1.*nix (Linux/Unix/Mac OS)

//
//  main.cpp
//  ColoredHelloWorld
//
//  Created by obaby on 14-2-27.
//  Copyright (c) 2014年 mars. All rights reserved.
//

#include 

//the following are UBUNTU/LINUX ONLY terminal color codes.
#define RESET   "\033[0m"
#define BLACK   "\033[30m"      /* Black */
#define RED     "\033[31m"      /* Red */
#define GREEN   "\033[32m"      /* Green */
#define YELLOW  "\033[33m"      /* Yellow */
#define BLUE    "\033[34m"      /* Blue */
#define MAGENTA "\033[35m"      /* Magenta */
#define CYAN    "\033[36m"      /* Cyan */
#define WHITE   "\033[37m"      /* White */
#define BOLDBLACK   "\033[1m\033[30m"      /* Bold Black */
#define BOLDRED     "\033[1m\033[31m"      /* Bold Red */
#define BOLDGREEN   "\033[1m\033[32m"      /* Bold Green */
#define BOLDYELLOW  "\033[1m\033[33m"      /* Bold Yellow */
#define BOLDBLUE    "\033[1m\033[34m"      /* Bold Blue */
#define BOLDMAGENTA "\033[1m\033[35m"      /* Bold Magenta */
#define BOLDCYAN    "\033[1m\033[36m"      /* Bold Cyan */
#define BOLDWHITE   "\033[1m\033[37m"      /* Bold White */

int main(int argc, const char * argv[])
{

    // insert code here...
    std::cout< 

2.Windows下面要用到一个api叫做:SetConsoleTextAttribute方法也比较简单。

// ColordCout.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include 
#include 

using namespace std;

void SetColor(unsigned short forecolor =4 ,unsigned short backgroudcolor =0)
{
	HANDLE hCon =GetStdHandle(STD_OUTPUT_HANDLE); //获取缓冲区句柄
	SetConsoleTextAttribute(hCon,forecolor|backgroudcolor); //设置文本及背景色
}

int _tmain(int argc, _TCHAR* argv[])
{
	SetColor(40,30);
	std::cout < <"Colored hello world for windows!\n";
	SetColor(120,20);
	std::cout <<"Colored hello world for windows!\n";
	SetColor(10,50);
	std::cout <<"Colored hello world for windows!\n";
	return 0;
}

☆版权☆

* 网站名称:obaby@mars
* 网址:https://h4ck.org.cn/
* 个性:https://oba.by/
* 本文标题: 《std::cout彩色输出》
* 本文链接:https://h4ck.org.cn/2014/02/5435
* 短链接:https://oba.by/?p=5435
* 转载文章请标明文章来源,原文标题以及原文链接。请遵从 《署名-非商业性使用-相同方式共享 2.5 中国大陆 (CC BY-NC-SA 2.5 CN) 》许可协议。


猜你喜欢:

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注