std::cout彩色輸出



Mac OS效果

Windows
Windows 效果

想寫這個東西其實是因為最近要寫個命令行的工具,但是有個問題是什么呢?就是傳統的那個黑漆漆的窗口看起來很蛋疼。並且完全看不到重點,於是就想起 來這么一個東西。相對來說針對*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   "\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< <RED      <<"Hello, World! in RED\n";
    std::cout<<GREEN    <<"Hello, World! in GREEN\n";
    std::cout<<YELLOW   <<"Hello, World! in YELLOW\n";
    std::cout<<BLUE     <<"Hello, World! in BLUE\n";
    std::cout<<MAGENTA  <<"Hello, World! in MAGENTA\n";
    std::cout<<CYAN     <<"Hello, World! in CYAN\n";
    std::cout<<WHITE    <<"Hello, World! in WHITE\n";
    std::cout<<BOLDRED  <<"Hello, World! in BOLDRED\n";
    std::cout<<BOLDCYAN <<"Hello, World! in BOLDCYAN\n";
    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!\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;
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM