Color changing function for printing text

So posting in this forum to help someone (http://www.cplusplus.com/forum/beginner/77879/), I noticed that the function I tought of did'nt work as I would want. I can't have more than 1 different color per cout. Can someone help me?:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <windows.h>
using namespace std;

char* Color(int color = 7, char* Message = ""){
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
    return Message;
}

int main()
{
    cout << Color(12,"\n Hey! I'm in color!") << Color(10," Nice C:\n");
    cin.get();
    return 0;
}


What I get is a completely red output!
Last edited on
Why do you define the color in the beginning? Just curious, I have no idea why it doesn't allow that.

I would simply make the different colors in different lines. That way you don't have to worry about making it any harder than it has to be, and we know that works.
What do you mean by "in the beggining"? In the beggining of the function, or the beggining of int main? What's a better option?
And sometimes it's better to have multiple color changes in a single statement. Probably only sometimes.
@samrux

Very nicely done. I'm not sure why the color variable still changes when you call the Color routine. I added in a little to show all 255 colors for you.

EDIT :: Understand why the declaring of variables now. Added them back into this program, and also added in the call to reset color to default

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
// Color Text.cpp : main project file.

#include <iostream>
#include <windows.h>

using namespace std;

char* Color(int color = 7 , char* Message = "")
{
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
    return Message;
}

/*void Color(int color=7)  // To reset color to light gray on black
{
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
	
}*/

int main()
{
    int x,c;
	cout << Color(164,"\n Hey! I'm in color! ") << Color(188," Nice C++\n\n");
    for (x=0;x<16;x++)
	{
		for (c=0;c<16;c++)
		{
			cout << Color(x*16+(c)," A ");
		}
		cout << endl;
	}
	Color();
	cout << "\n\n\t\tThanks for looking";
		cin.get();
    return 0;
}
Last edited on
Topic archived. No new replies allowed.