How to change text and background color?

I want every character to be a different color.

for example, cout << "Hello world" << endl;

'H' would be red
'e' would be blue
'l' would be orange
and so on.

I know this can be done, I just don't know the code for it.

and I want to change the background color to white. How would I do that?
@jae

Here is a small program that does what you were wondering about. Hope it helps you.

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
// Colored Hello World.cpp : main project file.

#include <stdafx.h> // Used with MS Visual Studio Express. Delete line if using something different
#include <conio.h> // Just for WaitKey() routine
#include <iostream>
#include <string>
#include <windows.h>

using namespace std;

HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); // For use of SetConsoleTextAttribute()

void WaitKey();

int main()
{

	int len = 0,x, y=240; // 240 = white background, black foreground 
	
	string text = "Hello World. I feel pretty today!";
	len = text.length();
	cout << endl << endl << endl << "\t\t"; // start 3 down, 2 tabs, right
	for ( x=0;x<len;x++)
	{
		SetConsoleTextAttribute(console, y); // set color for the next print
		cout << text[x];
		y++; // add 1 to y, for a new color
		if ( y >254) // There are 255 colors. 255 being white on white. Nothing to see. Bypass it
			y=240; // if y > 254, start colors back at white background, black chars
		Sleep(250); // Pause between letters 
	}

	SetConsoleTextAttribute(console, 15); // set color to black background, white chars
	WaitKey(); // Program over, wait for a keypress to close program
}


void WaitKey()
{
	cout  << endl << endl << endl << "\t\t\tPress any key";
	while (_kbhit()) _getch(); // Empty the input buffer
	_getch(); // Wait for a key
	while (_kbhit()) _getch(); // Empty the input buffer (some keys sends two messages)
}
Last edited on
Topic archived. No new replies allowed.