Colorful Output
Colorful output can make your C++ programs more visually appealing and less flat. In this section, we will discuss how to print colorful output in the console using ANSI escape codes.
ANSI Escape Codes
ANSI escape codes are a standard for in-band signaling to control the cursor location, color, and other options on video text terminals. They are used to format text in the console and are supported by most modern terminals.
Here are some common ANSI escape codes that you can use to print colorful output in C++:
\033[0m: Reset all attributes\033[1m: Bold\033[2m: Faint\033[3m: Italic\033[4m: Underline\033[5m: Blink\033[30m: Black text\033[31m: Red text\033[32m: Green text\033[33m: Yellow text\033[34m: Blue text\033[35m: Magenta text\033[36m: Cyan text\033[37m: White text\033[40m: Black background\033[41m: Red background\033[42m: Green background\033[43m: Yellow background\033[44m: Blue background\033[45m: Magenta background\033[46m: Cyan background\033[47m: White background
You can combine these escape codes to create colorful output in the console. Here is an example of printing a message in red text with a blue background:
#include <iostream>
using namespace std;
int main() { cout << "\033[31;44mHello, World!\033[0m" << endl;
return 0;}and the output will be:
Hello, World!To make it easier to use ANSI escape codes in your C++ programs, you can define them as constants. Here is an example of defining some common ANSI escape codes as constants:
#include <iostream>
using namespace std;
#define RESET "\033[0m"#define BOLD "\033[1m"#define ITALIC "\033[3m"#define UNDERLINE "\033[4m"#define RED "\033[31m"#define GREEN "\033[32m"#define BLUE "\033[34m"
int main() { cout << BOLD << RED << "Red" << RESET << endl; cout << ITALIC << GREEN << "Green" << RESET << endl; cout << UNDERLINE << BLUE << "Blue" << RESET << endl;
return 0;}and the output will be:
RedGreenBlueThere are many other ANSI escape codes that you can use to format text in the console. However, keep in mind that not all escape codes will work, so make sure you test them first before using them in your programs.