Setting individual text colors in c++ - c++

I'm a beginner in C++ programming and I want to know how to set a text color for individual texts. I know how to set text colors using system("COLOR ..") but it applies color to ALL texts, not individual texts. There's a program I've been coding wherein when the text is "Yes" that "Yes" will be color green and when it is "No", that "No" will be color red. This is for console application.
cout<<"Available: ";
if(available == true){
//code for setting text colors to GREEN
}
else{
//code for setting text colors to RED
}
cout<<yesno;
//code for setting text colors back to WHITE
so the output will be like for example
Available: (textcolor="green")Yes(/textcolor)
Thank you for any help!

In addition to the existing answers, if you need a portable way of doing it and hide setting colors behind an API. There's a single header library rlutil, which does that for you, wrapping ANSI and Windows color and other console manipulations:
rlutil::setColor(rlutil::GREY)

You need to print your text using ANSI colour codes; but not all terminals support this - if colour sequences are not supported, garbage will show up.
Here is and example:
cout << "\033[1;31mbold red text\033[0m\n";
Here, \033 is the ESC character, ASCII 27. Followed by [, then one or two numbers separated by ;, and finally the letter m. See this table on Wikipedia for details.

Under Linux, you can do something like this:
#include <iostream>
using namespace std;
int main() {
cout << "\033[1;30mblack" << endl
<< "\033[1;31mred" << endl
<< "\033[1;32mgreen" << endl
<< "\033[1;33myellow" << endl
<< "\033[1;34mblue" << endl
<< "\033[1;35mmagenta" << endl
<< "\033[0mback to normal" << endl;
return 0;
}
Check this wiki for color table.
Under Windows, you can use SetConsoleTextAttribute, like this:
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE);
Check this page for all the character attributes.

Related

C++ Changing Text Color

I'm trying to change the color of the text in c++, the only answer I can find is for C and not C++. I have tried using conio.h but don't understand how to use it. Could anyone help with this?
Text coloring isn't really on the C++ side. In some unix terminals you could simply use codes like \e[0;31m message \e[0m directly in your program (although you might want to create an API for ease of use). However, this wouldn't work in a Windows console. It depends on the OS and terminal being used.
If you don't need to stick to non cross-platform library conio.h. I recommend to use cross-platform solution: header only, moderc C++ rang library. I use it in most of my projects, it's really easy to use
I found out how to change the color of text using windows.h. Here is an example of the code I used (copied from https://cboard.cprogramming.com/).
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); // h is your link to the console
SetConsoleTextAttribute(h, 1); cout << "Sentence in blue" << '\n'; // 1 happens to be blue
SetConsoleTextAttribute(h, 2); cout << "Sentence in green" << '\n'; // 2 is green
SetConsoleTextAttribute(h, 4); cout << "Sentence in red" << '\n'; // 4 is red
SetConsoleTextAttribute(h, 7); cout << "Sentence in white" << '\n'; // etc.
}

I want to make my console more colorful. How can I make the user input (obtained through getline) colorful while they type?

I was just wondering if it is possible to color text while the user is typing it into the console.
I am using a color library for cout'ed text, but I wanted to know if it's possible to color the text while the user is inputting his/her string?
You can use Windows console APIs to do so:
HANDLE console_output = ::GetStdHandle(STD_OUTPUT_HANDLE);
::SetConsoleTextAttribute(console_output, FOREGROUND_GREEN);
std::string buffer;
std::getline(std::cin, buffer);
std::cout << buffer << std::endl;
::CloseHandle(console_output);
Input text will be green in color. Also, don't forget to include windows.h
On linux/macOS just do as following :
#include <iostream>
int main()
{
std::string foo;
std::cout << "Type your text here : \x1B[31m";
std::cin >> foo;
std::cout << "\x1B[0m" << std::endl;
std::cout << "Your input : " << foo << std::endl;
return (0);
}
A litte explanation :
when you type one of the followings specific strings :
"\x1B[31m" (red)
"\x1B[32m" (green)
"\x1B[33m" (yellow)
"\x1B[34m" (blue)
"\x1B[35m" (magenta)
"\x1B[36m" (cyan)
"\x1B[0m" (reset)
it will use termcap (stand for terminal capabilities) and change the color of all the output written after.
Don't forget to reset after using these termcap otherwise your terminal will stuck to the chosen color until you reset it.
PS : Don't know if it works for windows.

How can i change colors in c++?

So i searched for it and i found many answers. I found that in c++ there's no standard cross-platform way to do that and that the operative system manages colors. For example i found that on windows you can use the system("color 1") statement to change color to the text ( or foreground) and the system("color A") to change color to the background, or both system("color 1A") to change both. But this will change the whole colors, and i was wondering if there was a way to change it like even for a single character. Like take the program that i just did as an example:
#include<iostream>
using namespace std; /* I prefer to use this because i think that's a huge time saver and it's also easier*/
void printRoad(int i) /* That's my function, so by this function it prints a number of times choosed by the user 4 pieces of road*/
{
int counter=1;
while (counter <= i)
{
system("color 2"); /*Here is what i was talking about. I used the system("color 2") statement to change the text color
from the default to green, but it changes the whole text.*/
cout << "** | **" << endl;
cout << "** | **" << endl;
cout << "** | **" << endl;
cout << "** | **" << endl;
counter++;
}
};
void main() /*I don't need any specific return value from either the main() and the function so i thought it was a good idea to
just use void.*/
{
cout << "How many piece of roads do you want to build?" << endl; /*Here it asks to the user what to do.*/
int pieces = 0;
cin >> pieces;
printRoad(pieces); //Here is the function call.
system("pause"); /* Because i'm using windows and i'm using Visual Studio Express 2013 I used system("pause") to pause
the program and let the user see the output.*/
}
So what if, for example, i'd like to change each piece of road color? Like the first cout<<"** | **"<
I also read many people complaining about the use of system("") statements. I understand it because by doing so your program lose the cross-platform ability. But if the thing is dependent on the system we're on, how should we do it by keeping the cross-platform ability? Thanks for any answer.
Actually you can use this instead of calling system():
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), ValueOfColour);
As far as I understood your problem, you only want a certain character to be in your choosen colour. Then you need to change it back to the default value white/grey after this character was printed.

In C/C++, how do you edit a certain 'coordinate' in stdout?

I've been using Vim a lot lately, and I was wondering how the program manages to change the characters at certain positions in the terminal. For example, when using :rc, it replaces the character under the cursor with c.
I have also seen similar things done with Homebrew, which prints a progress bar to the screen and updates it when necessary.
How is this done in C/C++?
There is no standard way of doing this in C++.
It is done with OS dependent lbiraries, such as curses and similar libraries (ncurses) in the Unix/Linux world. Some of these libraries have been ported on across platforms (example: PDCurses)
For very simple things such as a progress bar or a counter, and as long as you remain on a single line there is the trick of using "\r" (carriage return) in the output, to place the cursor back at the begin of the current line. Example:
for (int i = 0; i < 100; i++) {
cout << "\rProgress: " << setw(3) << i;
this_thread::sleep_for(chrono::milliseconds(100));
}
Certainly, using ncurses or similar library is a good answer. An alternative may be to use ANSI Escape Codes to control the cursor in some terminal emulators (but not Windows command shell). For example, this code prints a line in multiple colors and then moves the cursor to 2,2 (coordinates are 1-based with 1,1 being the upper left corner) and prints the word "red" in the color red.
#include <iostream>
#include <string>
const std::string CSI{"\x1b["};
const std::string BLUE{CSI + "34m"};
const std::string RED{CSI + "31m"};
const std::string RESET{CSI + "0m"};
std::ostream &curpos(int row, int col)
{
return std::cout << CSI << row << ';' << col << 'H';
}
int main()
{
std::cout << "This is " << BLUE << "blue" << RESET << " and white.\n";
curpos(2,2);
std::cout << RED << "red" << RESET << '\n';
}
As mentioned that's not a matter of any C/C++ standard operations provided with stdout or cout (besides writing the necessary control characters to the screen).
Controlling the screen cursor of an ASCII terminal totally depends on implementation of the particular terminal program used, and besides a very narrow set of control characters, there's no standard established.
There are libraries like ncurses for a broader variety of linux terminal implementations, or PDcurses for a windows CMD shell.
I'm not sure to understand you completely but with creating an array of 100 elements of type char you can modify any position of the array and loop it with a std:cout to mostrate it on the console.
Perhaps could be better define the array of 50 chars to resuce the size of the printed result.
For example, if you have to print a progessbar in the 1% process, you should print:
Char progressbar[100] = {'X','','','','','','','','',........}

Colors in C++ win32 console

std::cout << "blblabla... [done]" << std::endl;
Is it possible to make [done] be in another color, and possibly bold? I'm using Windows 7
This depends on which OS you are using.
If you're using windows you want SetConsoleTextAttribute:
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); // Get handle to standard output
SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE);
You can also combine values.
An application can combine the
foreground and background constants to
achieve different colors. For example,
the following combination results in
bright cyan text on a blue background.
FOREGROUND_BLUE | FOREGROUND_GREEN |
FOREGROUND_INTENSITY | BACKGROUND_BLUE
You can then use WriteFile or WriteConsole to actually write the the console.
Yes, you just send a standard escape sequence, e.g.
const char* green = "\033[0;32m";
const char* white = "\033[0;37m";
const char* red = "\033[0;31m";
double profit = round(someComplicatedThing());
std::cout << (profit < 0 ? red : (profit > 0 ? green : white))
<< "Profit is " << profit << white << std::endl;
You also get bold vs normal, colored background etc. The Wikipedia page on ANSI escape code has details, the Bash-Prompt HOWTO has examples.
You can use this tiny libraries which I have used personally before. It is very easy to use and integrate with standard streams. It has a clear console screen functionality btw. This example is from a code I wrote:
std::cout << con::clr; // Clear the Intro Screen
// fg means the foreground
std::cout << std::endl << std::endl << con::fg_green
<< "\t\tFile Encrypted!";
Yes you can you can use the system(); function to run commands from the command.com and one of those is color.
color a will get you the green you want.
you may also see other colors from the help option color /? .
and for the bold thing you can use characters from ascii chart to do that.
such as "\n" Is Newline.
A quick way: include #include <stdlib.h> and then add system( "color 5B" ); before the text you want. So it will look like this:
#include <stdlib.h>
std::cout << "blblabla..."<<std::endl;
system( "color 5B" );
std::cout<< "[done]" << std::endl;
You can try different colors: 1A, 2B, 3C, 4F...