Different Color Text

Dec 12, 2014 at 3:43am
How do I change the color of text in c++. I've used system("color") to change all the text of the console output, but I need to find out how to do with just two letters that belong to two different variables.

Dec 12, 2014 at 3:50am
Dec 12, 2014 at 4:14am
thank you Duoas! Also I accidentally reported your post.
Dec 12, 2014 at 4:20am
alright how do I assign a color to a variable. Tried this retard assignment, but it obviously didn't work. I want name2 to be printed in standard console color and name to be printed in whatever color I tried assigning it here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

using namespace std;

int main()
{
    string name = "Ricky";
    string name2 = "Jake";
    name =  SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ), 0xE4 );
    cout << name << endl;
    cout << name2 << endl;


    return 0;
}

Last edited on Dec 12, 2014 at 4:21am
Dec 12, 2014 at 4:57am
you can't assign a color to a variable you have to change the color manually

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
#include <windows.h>

using namespace std;

int main()
{
	HANDLE std_output = GetStdHandle(STD_OUTPUT_HANDLE);
	
	string name = "Ricky";
	string name2 = "Jake";
	
	
	SetConsoleTextAttribute(std_output, FOREGROUND_BLUE);
	cout << name << endl;
	
	
	SetConsoleTextAttribute(std_output, FOREGROUND_GREEN);
	cout << name2 << endl;

	std::cin.ignore();
	return 0;
}
Last edited on Dec 12, 2014 at 4:58am
Dec 12, 2014 at 6:01am
Okay so I'm pretty sure what I want to do for my program is impossible since you can't assign a color to a variable. I wanted to make the X's yellow and the O's red for my tic tac toe game. I'm passing both letters by reference.
Dec 12, 2014 at 6:34am
it's not impossible you just need to get creative.
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
#include <iostream>
#include <Windows.h>
char color_char(const char inChar);

int main()
{
	const int SIZE = 10;
	char arr[SIZE] = "xOhelXjio";

	for (unsigned i = 0; i < SIZE; ++i)
		std::cout << color_char(arr[i]);


	std::cin.ignore();
	return 0;
}

char color_char(const char inChar)
{
	HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
	int color = 0;
	switch (inChar)
	{
		break;
	case 'X':
	case 'x':
		color = 12; //bright red
		break;
	case 'O':
	case 'o':
		color = 14; //bright yellow
		break;
	default:
		color = 7; //gray
		break;

	}
	SetConsoleTextAttribute(hcon, color);
	return inChar;
}
Last edited on Dec 12, 2014 at 6:34am
Topic archived. No new replies allowed.