Colors in C++ win32 console - c++

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

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

Atomically write colored text to console in Windows

I need to print to console some output with color content. Is it possible to do in windows atomically? In Linux there is ansi colors support and it is really very convenient to do complex colored sentences. What about windows? I can do the following:
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
printf(" this is how it starts ");
SetConsoleTextAttribute(hConsole, 10);
printf("YES, it should be green ");
SetConsoleTextAttribute(hConsole, 0);
printf("back to standard color\n");
It seems to me that in asynchronous app this 3 printf will not print text at the same line in console. Here comes 2 solutions in my mind:
1) Use mutex for syncing all console output so as all messages appear sequentially. Seems an overkill solution for such problem.
2) Use some method to stop console output for a while, print colored line and then start output again.
So, my concern is getting colored line without breaks made by other asynchronous output. Is it possible in windows and what is the best approach?
As #eryksun said, use WriteConsoleOutput instead of printf/std::cout.
This is the same as any graphical application. Only one thread does all the writing. It has a queue which contains a list of strings and attributes. When a thread wishes to print something, it pushes the string and the relevant attribute into the queue. Before printing the writing thread sets the attribute and then prints the string.
You will need to implement your own thread-safe queue. Mine are normally low volume outputs so I use an array of 256 with a uint8_t counter and atomic markers. There is no boundary checking: uint8_t wraps back to 0 after 255. Circular queues work quite well.
You can create a very simple class to do the writing. I normally use something like this. Scribbler is the class that does the writing to the screen
class COut : public std::ostringstream
{
Scribbler* writer;
WORD attr;
public:
COut(WORD in_attr)
{
attr = in_attr;
writer = Scribbler::Me();
}
COut& operator << (std::ostream&(*f)(std::ostream&))
{
if (f == std::endl)
{
*this << "\n";
writer->Push(attr, str());
str("");
}
else
{
*this << f;
}
return *this;
}
template <typename TT>
inline COut& operator << (const TT& t)
{
(*(std::ostringstream*) this) << t;
return *this;
}
};
This can be used like std::cout and it will do everything you can do with std::cout. Alternatively, you can write a variant of printf but it isn't that simple when you get into the depths of passing std::arg all over the place.
The thread wanting yellow output would do something like
COut yout(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY);
...
yout << "Yellow, yellow dirty fellow" << std::hex << std::setfill('0') << std::setw(4) << 25 << std::endl;
The thread wanting magenta output would do
COut mout(FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
...
mout << ... << std::endl;
Nothing gets printed until a std::endl is issued. You can get quite creative with this with different threads writing to different scrollable parts of the screen using SetConsoleWindowInfo. It will work as long as there is only one thread that does the writing. All the other threads just tell it where to write the output and its colour attributes.

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.

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.

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