想写这个东西其实是因为最近要写个命令行的工具,但是有个问题是什么呢?就是传统的那个黑漆漆的窗口看起来很蛋疼。并且完全看不到重点,于是就想起 来这么一个东西。相对来说针对*nix的系统方法会比较通用一些,而windows下这个东西需要用到专门的Windows相关的api来实现。
下面先说通用的方法:
1.*nix (Linux/Unix/Mac OS)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
// // main.cpp // ColoredHelloWorld // // Created by obaby on 14-2-27. // Copyright (c) 2014年 mars. All rights reserved. // #include <iostream> //the following are UBUNTU/LINUX ONLY terminal color codes. #define RESET " 33[0m" #define BLACK " 33[30m" /* Black */ #define RED " 33[31m" /* Red */ #define GREEN " 33[32m" /* Green */ #define YELLOW " 33[33m" /* Yellow */ #define BLUE " 33[34m" /* Blue */ #define MAGENTA " 33[35m" /* Magenta */ #define CYAN " 33[36m" /* Cyan */ #define WHITE " 33[37m" /* White */ #define BOLDBLACK " 33[1m 33[30m" /* Bold Black */ #define BOLDRED " 33[1m 33[31m" /* Bold Red */ #define BOLDGREEN " 33[1m 33[32m" /* Bold Green */ #define BOLDYELLOW " 33[1m 33[33m" /* Bold Yellow */ #define BOLDBLUE " 33[1m 33[34m" /* Bold Blue */ #define BOLDMAGENTA " 33[1m 33[35m" /* Bold Magenta */ #define BOLDCYAN " 33[1m 33[36m" /* Bold Cyan */ #define BOLDWHITE " 33[1m 33[37m" /* Bold White */ int main(int argc, const char * argv[]) { // insert code here... std::cout< <RED <<"Hello, World! in RED "; std::cout<<GREEN <<"Hello, World! in GREEN "; std::cout<<YELLOW <<"Hello, World! in YELLOW "; std::cout<<BLUE <<"Hello, World! in BLUE "; std::cout<<MAGENTA <<"Hello, World! in MAGENTA "; std::cout<<CYAN <<"Hello, World! in CYAN "; std::cout<<WHITE <<"Hello, World! in WHITE "; std::cout<<BOLDRED <<"Hello, World! in BOLDRED "; std::cout<<BOLDCYAN <<"Hello, World! in BOLDCYAN "; return 0; } |
2.Windows下面要用到一个api叫做:SetConsoleTextAttribute方法也比较简单。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// ColordCout.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <windows .h> 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! "; SetColor(120,20); std::cout <<"Colored hello world for windows! "; SetColor(10,50); std::cout <<"Colored hello world for windows! "; return 0; } |
原创文章,转载请注明: 转载自 火星信息安全研究院
本文标题: 《std::cout彩色输出》
本文链接地址: http://www.h4ck.ws/2014/02/stdcout%e5%bd%a9%e8%89%b2%e8%be%93%e5%87%ba/