Switch to full style
For C/C++ coders discussions and solutions
Post a reply

print to console using the cout object with different Color

Sat Nov 08, 2008 11:35 pm

This example print to console using the cout object but this time with colors. , this code allow you to change the code you use for printing text on the CMD.




cpp code
// ChangeColor.h


#pragma once
#include <iostream>

#include <windows.h>


inline std::ostream& blue(std::ostream &s)
{
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdout, FOREGROUND_BLUE
|FOREGROUND_GREEN|FOREGROUND_INTENSITY);
return s;
}

inline std::ostream& red(std::ostream &s)
{
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdout,
FOREGROUND_RED|FOREGROUND_INTENSITY);
return s;
}

inline std::ostream& green(std::ostream &s)
{
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdout,
FOREGROUND_GREEN|FOREGROUND_INTENSITY);
return s;
}

inline std::ostream& yellow(std::ostream &s)
{
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdout,
FOREGROUND_GREEN|FOREGROUND_RED|FOREGROUND_INTENSITY);
return s;
}

inline std::ostream& white(std::ostream &s)
{
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdout,
FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE);
return s;
}

struct color {
color(WORD attribute):m_color(attribute){};
WORD m_color;
};

template <class _Elem, class _Traits>
std::basic_ostream<_Elem,_Traits>&
operator<<(std::basic_ostream<_Elem,_Traits>& i, color& c)
{
HANDLE hStdout=GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdout,c.m_color);
return i;
}

Example of using the package:
cpp code
#include "ChangeColor.h"


std::cout << green << "Green text"
<< white << std::endl;
std::cout << color(FOREGROUND_RED|FOREGROUND_GREEN)
<< "Really done. !"
<< white << std::endl;




Post a reply
  Related Posts  to : print to console using the cout object with different Color
 Print the content of hashMap object     -  
 What is PHP Console     -  
 Help for Print using php     -  
 Print the ASCII Set     -  
 Print all server variables     -  
 print clock using JavaScript     -  
 How to print a webcam picture in Jsp     -  
 Print all MySQL status value     -  
 Print all files in a directory     -  
 print element in 2d matrix     -  

Topic Tags

C++ Basics