colors in console for beginners

How to write c++ console application that prints colored text onscreen?

I want make "Hello World" where hello is in red color and world is in blue color.
At the moment I have this code.
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

using namespace std;

int main()
{
  cout<<"HEY, you, I'm alive! Oh, and Hello World!\n";
  cin.get();

  return 1;
}


And what should i do next in C++? Where I can find some (millions of) examples for beginners?
Give this a shot, as you can see "system("Color 1A");" changes the color. Look the code up and find out what all the colors are by replaceing the 1 and the A

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
#include <iostream>

int main()
{	
	while(true)
	{
		system("Color 1A");
		std::cout << "\t\t\t    Hello World" << std::endl;
		system("Color 2B");
		std::cout << "\t\t\t    Hello World" << std::endl;
		system("Color 3C");
		std::cout << "\t\t\t    Hello World" << std::endl;
		system("Color 4D");
		std::cout << "\t\t\t    Hello World" << std::endl;
		system("Color 5E");
		std::cout << "\t\t\t    Hello World" << std::endl;
		system("Color 6F");
		std::cout << "\t\t\t    Hello World" << std::endl;
		system("Color A1");
		std::cout << "\t\t\t    Hello World" << std::endl;
		system("Color B2");
		std::cout << "\t\t\t    Hello World" << std::endl;
		system("Color C3");
		std::cout << "\t\t\t    Hello World" << std::endl;
		system("Color D4");
		std::cout << "\t\t\t    Hello World" << std::endl;
		system("Color E5");
		std::cout << "\t\t\t    Hello World" << std::endl;
		system("Color F6");
		std::cout << "\t\t\t    Hello World" << std::endl;
	}
	return 0;
}
*ahem*

Please don't tell people to use system(). If you are going to do something OS-dependant, do it the right way.

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
#include <iostream>
#include <windows.h>

int main()
{
	const WORD colors[] =
		{
		0x1A, 0x2B, 0x3C, 0x4D, 0x5E, 0x6F,
		0xA1, 0xB2, 0xC3, 0xD4, 0xE5, 0xF6
		};

	HANDLE hstdin  = GetStdHandle( STD_INPUT_HANDLE  );
	HANDLE hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
	WORD   index   = 0;

	// Remember how things were when we started
	CONSOLE_SCREEN_BUFFER_INFO csbi;
	GetConsoleScreenBufferInfo( hstdout, &csbi );

	// Tell the user how to stop
	SetConsoleTextAttribute( hstdout, 0xEC );
	std::cout << "Press any key to quit.\n";

	// Draw pretty colors until the user presses any key
	while (WaitForSingleObject( hstdin, 100 ) == WAIT_TIMEOUT)
	{
		SetConsoleTextAttribute( hstdout, colors[ index ] );
		std::cout << "\t\t\t\t Hello World \t\t\t\t" << std::endl;
		if (++index > sizeof(colors)/sizeof(colors[0]))
			index = 0;
	}
	FlushConsoleInputBuffer( hstdin );

	// Keep users happy
	SetConsoleTextAttribute( hstdout, csbi.wAttributes );
	return 0;
}


Hope this helps.

[edit] Oh, yeah, colors are bit-encoded thus:

bit 0 - foreground blue
bit 1 - foreground green
bit 2 - foreground red
bit 3 - foreground intensity

bit 4 - background blue
bit 5 - background green
bit 6 - background red
bit 7 - background intensity

:-)
Last edited on
Duoas. I have read the sticky topic where you almost make a quarrel about this.

Personally, I don't understand a word of what you said, because I'm still not well developed in C++ language. Unlike your code, the system() is easier to comprehend for beginniners. The Hello world is the first program you see in the tutorial, meaning that it's for beginners. :D

I'm not discouraging you of writing such stuff, but you could at least post it in topics a little more complicated that "Hello World".

I hope that you didn't take offense in what I said. I only said what was in my mind! :D
Thanks for the feedback. Sometimes my presentation needs work.

However, the reason I continue to post this stuff is exactly because you are a beginner (and don't know any better).

Frankly, all those book authors and university professors teaching people to use system() to set console colors and the like are doing you (that is, beginners) a terrible disservice. People who claim to be your friend and instruct you to run around with knives really don't have your best interests at heart. They ought to be shot. (Along with virus writers.) Because they know better.


Forgetting everything other than what it takes to be "easy" for beginners, there is only one difference between
1
2
3
#include <stdlib.h>

system( "color 5B" );

and
1
2
3
#include <windows.h>

SetConsoleTextAttribute( GetStdHandle( STD_INPUT_HANDLE ), 0x5B );

The difference is the number of words you have to memorize -- or letters you have to type.

Don't complain about some extra letters. It is never too much of an inconvenience to do things the right way. (Which is the whole point.)

The bonus is: you have learned how to do something safely and quickly, you won't be treated like a loser-wannabe by other programmers, you'll be more valuable to your employer, and you'll be better able to learn and understand new things about handling the console than otherwise.

MS is a funny master. I know their website presents things using system() as examples. But if you tried to get a job at Microsoft with such code they would be showing you out the door before it had time to close after you first entered.


Mythios himself is still a beginner. In other words, he is still learning. What he has going for himself is that he is working hard at learning new things and when he learns something new or cool -- he does something with it. When he learns something that previously perplexed him -- he posts to help others get past that same problem.

If you had cared to actually compile and run our two programs, you would have noticed that they behaved almost identically -- the difference is that I improved it some. His only ends when the user presses Ctrl-C or otherwise kills the program. Mine ends properly by pressing any key. It also tells you how to quit and slows down the output a little bit. I also moved all those colors into an indexable array, instead of repeating the same statement over and over and over in the big loop.

Again, I appreciate the feedback; I realize that I didn't very carefully explain the improvements I made. However, the commentary really is sufficient to follow along. Programming is a very exacting discipline: it requires you to pay attention to all the little details.


Being a beginner does not mean things should be "easy". It means that you still have stuff to learn. Learn it.

If it goes over your head, and a lot of it will at first, either ignore it, or cut and paste it to use it, or study it until you understand it well. Please don't complain about it. (But please do offer suggestions on how I can better present it.) Believe it or not, just because I'm not a "beginner" doesn't mean I am not learning new stuff the same way all the time. It took me a year to wrap my head around network protocols.

Hope this helps.

The problem there is no support for colors in C++ so having that in a C++ tutorial is not a good thing. Colors are a part of the operating system environment you are in. Some OS don't even have a console.

So if you are googling for a generic solution you will not find one, instead you need to find a solution for 'your' OS since it hasn't to do with C++.
LoL Duoas you convinced me. But I just re-read your code, and well ok the commentary helps, but some things are still vague, and I don't know what use are they for. Thus, I would only be copy-pasting things into my command line without knowing what each specific thing does. I know you will tell me to search some websites to increase my knowledge, but sometimes that doesn't help. In the tutorial given by this website, I still don't understand a lot of things! I don't know what they are for!!

Thanks for your feedback as well :D.
Last edited on
I am actually writing a pretty comprehensive tutorial on all this console junk right now... You'll probably see it in the Articles forum by the end of the month.

The wierdest parts above are the WaitForSingleObject() --which is being used pretty much like kbhit()-- and FlushConsoleInputBuffer() --which reads and tosses whatever key was pressed.

For Microsoft, more often than not useful google terms are things like

msdn waitforsingleobject
msdn flushconsoleinputbuffer
msdn getconsolescreenbufferinfo

etc.

I haven't actually read the "Hello world" tutorial on this site... I'll have to go do that now... :-S
Last edited on
I didn't mean the Hello World tutorial that was a bit hard for me. I mean the more advanced stuff such as the "Dynamic Memory" & "Pointers" and so. Some parts I didn't understand so I skipped them :( . That's why I feel as if I don't understand anything :(
Ah, LOL. Don't fret about it. You'll wrap your head around it all in no time. Just keep going at it and it will come.

;-)
Ok. Thnx :D
Topic archived. No new replies allowed.