Sign in to follow this  
mattnenterprise

how to make color output in C++

Recommended Posts

Only some window consoles can pull this off. I believe it would go something like this?

int main()
{
system("COLOR C");
std::cout << "I'm a different color!\n";
system("COLOR A");
std::cout << "And I'm another color as well.\n";
system("PAUSE");
return 0;
}



Look up on Google the different colors, but I think that's how you would go about it.

~Maverick

Share this post


Link to post
Share on other sites
C++ doesn't have the ability to make color output.

What you need to do is find a library which can support what you're looking for. I'd honestly use a system specific library before I'd ever use a System() to do something.

If using a console in Windows, you can use the function SetConsoleTextAttribute.

*EDIT*

An example:


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

int main()
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole,FOREGROUND_RED);
std::cout << "Hello Red World" << std::endl;
return 0;
}





[Edited by - Nytegard on July 27, 2008 11:58:50 PM]

Share this post


Link to post
Share on other sites
You can directly access the video memory:



char far *v=(char far *) 0xB8000000;

void printc(char c,int row,int colum,int color)
{
*(v+((160*row)+(2*colum)))=c;
*(v+((160*row)+((2*colum)+1)))=color;
}


Share this post


Link to post
Share on other sites
Also, color values for text with a black background range from 0-15, so if you want to the change text color constantly, you can play around with color values between 0-15.


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

int main()
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
int color = 0, i;

for (i = 0; i < 16; i++)
{
SetConsoleTextAttribute(hConsole, color);
std::cout << "I'm a different color!" << std::endl;
color++;
}

system("pause");
return 0;
}



Also, you can change the background color like this.

SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE | BACKGROUND_GREEN);
std::cout << "Blue text with green background" << std::endl;

Share this post


Link to post
Share on other sites
Alright, I'm probably going to be attacked on this, but

DO NOT USE system("pause")!!! Heck, like I stated before, try avoid anything that uses system().

Try something else like


#include <iostream>
#include <limits>

#ifdef _MSC_VER
#undef max
#endif

int main()
{
std::cout << "Press Enter to continue..." << std::endl;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

return 0;
}






It's late, so I'm not going to go further into this, but if you need to know why, search for one of the many threads on system(pause).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this