Changing Color of command box

I just discovered you could use system ("color 2") to change the text color and background color of the command box and I was wondering If you could have the user input a number and have it change the color of the box. Appearently it needs to be a string literal but I dont want to have the user type something like "color 23" just 23.


This is my attempt to do this:
1
2
3
4
5
6
int main()
{
	char x = '0';
	cin >> x;
	system ("color " + x);
}
Last edited on
You can use C++ strings
eg:
1
2
3
string color;
cin >> color;
system("color "+color);


Or (Better) Win API functions (SetConsoleTextAttribute) if on a Windows operating system

http://msdn.microsoft.com/en-us/library/ms686047(VS.85).aspx
Thank you
I love the speed of the replys here
Nevermind I get an error that says:

1>c:\users\ed\desktop\mits calculator\mits calculator\mits calculator .cpp(29) : error C2664: 'system' : cannot convert parameter 1 from 'std::basic_string<_Elem,_Traits,_Ax>' to 'const char *'

Not sure what it means but I guess you cant use +color is there another way to do this (save the Win API thing)?
Yeah, I forgot that you have to convert the string in a C string:
system( ("color "+color).c_str() );

To use the Windows function, try this:
SetConsoleTextAttribute ( GetStdHandle ( STD_OUTPUT_HANDLE ) , color );
'color' is a number made of two bytes, the higher is the background and the lower the foreground eg if color is 0x0C the result would be black background and red text. You can find some constants at http://msdn.microsoft.com/en-us/library/ms682088(VS.85).aspx

When you can avoid the 'system' function is better
Last edited on
Ok thank you again
Topic archived. No new replies allowed.