c++ print colorful
To print colorful output in C++, you can use escape sequences with the help of the ASCII codes. Here are the steps to achieve colorful printing in C++:
Include the necessary header file:
cpp #include <iostream>
Use escape sequences to change the color of the output. The escape sequence for changing color starts with the escape character
\033
followed by the code for the desired color. Here are some common color codes:Black:
\033[30m
- Red:
\033[31m
- Green:
\033[32m
- Yellow:
\033[33m
- Blue:
\033[34m
- Magenta:
\033[35m
- Cyan:
\033[36m
White:
\033[37m
Print the colored output using
std::cout
. After printing the colored text, you should reset the color to the default using the code\033[0m
. This ensures that the following output is not affected by the color change.
cpp
std::cout << "\033[31mRed text\033[0m" << std::endl;
std::cout << "\033[32mGreen text\033[0m" << std::endl;
std::cout << "\033[33mYellow text\033[0m" << std::endl;
In the above example, the text "Red text" will be printed in red, "Green text" will be printed in green, and "Yellow text" will be printed in yellow.
- Compile and run the program. You should see the colored output in your console.
Note: The effectiveness of the color codes may vary depending on the terminal or console you are using. Some terminals may not support these escape sequences, resulting in plain text being displayed instead.