C++ Changing Text Color - c++

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.
}

Related

How do I move the console cursor to (x, y) on unix?

I have used <windows.h> and <conio.h> on windows for this kind of thing, but on unix the only thing I can find is <ncurses.h>, which uses a lot of C and doesn't support a lot of C++ functions. How can I move the console cursor to (x, y), while also being able to do object-oriented programming?
Edit: I'm trying to make simple games in C++ using the console as a display. I know it's not ideal to do so, but this is for a project that can't use Visual C++ or any other graphics. Think something like snake or minesweeper. I need to be able to cout in different locations, without updating the entire screen in the process. It needs to be compatible with unix systems.
One very simple way is through ANSI escape codes:
#include <iostream>
void moveCursor(std::ostream& os, int col, int row)
{
os << "\033[" << col << ";" << row << "H";
}
int main()
{
moveCursor(std::cout, 1,1);
std::cout << "X (1,1)";
moveCursor(std::cout, 13,8);
std::cout << "X (13,8)" << std::endl;
return 0;
}
The sequence <ESC>[ row , col H (the escape character is ASCII 27 or octal '\033') performs absolut cursor positioning. On most common terminals this should place one "X" in the top-left corner, and the second in column 13, row 8 (counts are 1-based).
Edit: hvd’s comment is of course spot-on: This is very simple, but ncurses is complex for a reason. It is guaranteed to work more reliably and in a much wider variety of settings than a plain escape code. Depending on what you actually want to achieve, I agree with hvd that you should be very careful before picking this simple hack as the solution to your problem.

Setting individual text colors in 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.

Repeating loop until enter is pressed

For anybody else finding this question, this can be accomplished with the kbhit() function in the conio.h library. Just insert !kbhit() where I put SOMETHING and it will loop correctly, I am looking for a way to do this without a library, however.
I'm a beginner trying to create a simple animation in the console. The animation would have the word UP going up the right hand of the console and the word DOWN going down the right hand side. So far I have gotten the animation to complete one iteration of this, but I'm trying to make it so that it repeats and it looks like the texts wraps back to the top or bottom and does it again until the user presses the ENTER key.
My book (I'm self teaching from a textbook) makes it seem that its possible without any specific libraries except for iostream and windows.h but help that includes library functions is welcome too, it is a learning experience after all. Thanks a ton!
A little explanation of the code would be that I set the coordinates of the UP and DOWN starting positions and then move the cursor, delete the previous line it was on with a space and then increment two and put a new word. I would guess that I could use a second while loop to somehow check if the ENTER key has been pressed.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE);
COORD upPos = {20,28};
COORD downPos = {50, 0};
char endState;
while ( SOMETHING )
{
COORD upPos = {20,28};
COORD downPos = {50, 0};
while (upPos.Y >=0)
{
SetConsoleCursorPosition(screen,upPos);
cout << "UP" << endl;
upPos.Y++;
SetConsoleCursorPosition(screen,upPos);
cout << " " << endl;
upPos.Y -=2;
SetConsoleCursorPosition(screen,downPos);
cout << "DOWN" << endl;
downPos.Y--;
SetConsoleCursorPosition(screen,downPos);
cout << " " << endl;
downPos.Y+=2;
Sleep(100);
}
}
}
Your best bet is to create a custom "GetAsyncKeyState" function that will use #IFDEF for windows and linux to choose the appropriate GetAsyncKeyState() or equivalent. For ex
if (GetAsyncKeyState(VK_RETURN))
{
exit = true;
}

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...