Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

I'm looking for strings in c++ to change some colors

+3 votes
asked Feb 1, 2025 by Spippolo (150 points)
I'm looking for strings in c++ to change some colors

3 Answers

0 votes
answered Feb 1, 2025 by Peter Minarik (101,340 points)
0 votes
answered Feb 17, 2025 by cpp guy (1,020 points)

if you want to change colours in c++ with strings, look at this : 

For unix systems : 

#include <iostream>

#include <string>

using namespace std;

string colourtext = "\033[32mcoloured text" <-- \033[xxm is the ansi escape code for colours for unix systems.

int main() {

cout << colourtext;

return 0;

}

For Windows, you would use:

// with <cstdlib> library for system() 

system("color xx");

Hope this helped.

+1 vote
answered Mar 1, 2025 by Fuzail Sheriff (160 points)

You can do this using ANSI Escape Codes. To do this, you need to add, or concatenate, "\033m[38;2;" + <r> + ";" + <g> + ";" + <b> + "m" + <text> + "\033[0m", where <r>, <g>, and <b> are your R, G, and B values respectively and <text> is the string you want to color. "\033m[0m" is necessary to return the style to normal, otherwise all text after would also be colored. You can easily do this using a function.

Code:

#include <iostream>

void rgbText(std::string text, int r, int g, int b) {
      
      //adds color to the text  
      std::cout << "\033[38;2;" << r << ";" << g << ";" << b << "m" << text << "\033[0m" << std::endl;

}

int main() {

      rgbText("This is Cyan!", 0, 255, 255); //Cyan Color

      rgbText("This is Red!", 255, 0, 0); //Red Color

      return 0;

}

Output:

This is Cyan!

This is Red!

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...