How to change a sentence color?

I'd love to change this sentence color

cout << "CALCULATOR\nMade by Kristen\n\n";

It's white in console, how can I change it? Working in Code::Blocks
Vague possibility of this working in the Windows command window / console.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <map>
#include <string>
#include <windows.h>
using namespace std;

map<string,int> cmap = {
                        { "Black"       , 0  },
                        { "Blue"        , 1  },
                        { "Green"       , 2  },
                        { "Aqua"        , 3  },
                        { "Red"         , 4  },
                        { "Purple"      , 5  },
                        { "Yellow"      , 6  },
                        { "White"       , 7  },
                        { "Gray"        , 8  },
                        { "Light_Blue"  , 9  },
                        { "Light_Green" , 10 },
                        { "Light_Aqua"  , 11 },
                        { "Light_Red"   , 12 },
                        { "Light_Purple", 13 },
                        { "Light_Yellow", 14 },
                        { "Bright_White", 15 } };

HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE );


void color( string s )
{
   SetConsoleTextAttribute( h, cmap[s] );        // need to add some checking ... job for another day
}


int main()
{
   for ( auto e : cmap ) 
   {
      color( e.first );   cout << e.first << '\n';
   }

   cout << '\n';
   color( "Blue"  );   cout << "You wanted a sentence in blue" << '\n';
   color( "Red"   );   cout << "And another one in red?"       << '\n';
   color( "White" );   cout << "Better tidy up though"         << '\n';
}
Just as @lastchance said, you can do that, tough i would not suggest it, since you are making a calculator, you are probably a begginer, so i would suggest using system();
You can use cmd to try color combinations. Just press Win+R and type cmd. There use the command color to use it.
Quote from CMD:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Sets the default console foreground and background colors.

COLOR [attr]

  attr        Specifies color attribute of console output

Color attributes are specified by TWO hex digits -- the first
corresponds to the background; the second the foreground.  Each digit
can be any of the following values:

    0 = Black       8 = Gray
    1 = Blue        9 = Light Blue
    2 = Green       A = Light Green
    3 = Aqua        B = Light Aqua
    4 = Red         C = Light Red
    5 = Purple      D = Light Purple
    6 = Yellow      E = Light Yellow
    7 = White       F = Bright White

If no argument is given, this command restores the color to what it was
when CMD.EXE started.  This value either comes from the current console
window, the /T command line switch or from the DefaultColor registry
value.


and this is how you would use it in a program
[code]
#include <iostream>
#include <cstdlib>

using namespace std;

int main() {
system("color 3");
cout<<"Hello"<<endl;
return 0;
}
@masecla33,

Even being prepared to take the flak for using system(), this will change ALL the console output - not on a sentence-by-sentence basis. Try typing successively
color 3
color 4
color 5

into a command window and see what happens to your previous text.

Last edited on
I am aware of it, but implementing the windows based color, is very hard for begginers, and the most they can do is copy paste the code everytime, and not learning anything.
I am aware of it, but implementing the windows based color, is very hard for beginners

Harder than the friggin' two-line GetStdHandle()/SetConsoleTextAttribute() library calls exampled above? That's non-sequitur.

Your reasoning is specious too:
the most [beginners] can do is copy past the code everytime, and not learning anything

We all regularly use things with absolutely no idea how they work -- like compilers, web-browsers, image-editing software, speech recognition, friggin' cars and synchronized traffic lights, credit cards, refrigerators, ...

We program using libraries like <algorithm> and <iostream> (and <cstdio>) and you have no idea what kind of madness happens underneath the surface, yet you have no problem telling user to #include <cstdlib> and use the magic system() function.

Knock it off. Teach people how to do things the right way, and when you make a mistake, man/woman up to it, and keep on trucking like the rest of us.

Please don't tell people to do stupid stuff. Cause someone's going to have to disabuse them of their mistaken knowledge later (maybe even at the cost of their job).
@kristen

It occurs to me that a simpler example might be more beneficial.
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <windows.h>                   // you will need this for the Windows console routines
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.
}


If you google "SetConsoleTextAttribute" you will find that you can do many other whacky things with this library routine ... but I don't want to be the one who tells you how to make your text blink!

In my first example I set up a color() function so that I could map more easily from a string name to a not-very-easily-remembered number. However, writing the simplified example above, I've just realised how RGB maps to the binary digits (I'm slow!)

Finally, the standard colours seem to be quite dark on my terminal and you would have to change the background colour as well to use them. I once got into trouble at work for changing a web-page colour scheme to one that it turns out can't be properly distinguished by those with the commonest form of colour-blindness. So ... use with caution.
Last edited on
Another option:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <windows.h>   

using std::cout;

enum class Color
{
  Blue = 1,
  Green,
  Red = 4,
  White = 7
};

BOOL SetForeColor(const Color& color)
{
  HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
  if (hConsole == INVALID_HANDLE_VALUE)
    return FALSE;

  if (!SetConsoleTextAttribute(hConsole, static_cast<WORD>(color)))
    return FALSE;

  return TRUE;
}

int main()
{
  SetForeColor(Color::Blue);
  cout << "Sentence in blue" << '\n'; 

  SetForeColor(Color::Green);
  cout << "Sentence in green" << '\n';      
  
  SetForeColor(Color::Red);
  cout << "Sentence in red" << '\n';        

  SetForeColor(Color::White);
  cout << "Sentence in white" << '\n';
}


OR

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <string>
#include <windows.h>   

using std::cout;
using std::string;

enum class Color
{
  Blue = 1,
  Green,
  Red = 4,
  White = 7
};

BOOL ColorPrint(const Color& color, string msg)
{
  HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
  if (hConsole == INVALID_HANDLE_VALUE)
    return FALSE;

  if (!SetConsoleTextAttribute(hConsole, static_cast<WORD>(color)))
    return FALSE;

  cout << msg;

  return TRUE;
}

int main()
{
  ColorPrint(Color::Blue, "Sentence in blue\n");
  ColorPrint(Color::Green, "Sentence in green\n");
  ColorPrint(Color::Red, "Sentence in red\n");
  ColorPrint(Color::White, "Sentence in white\n");

}
Add color to your console 2 [Windows source]:
http://www.cplusplus.com/articles/Eyhv0pDG/
Yeah... I dislike that article too. Here's something a little better:
http://www.cplusplus.com/forum/general/48596/#msg264748
None of the methods worked what you guys showed to me. They all changed whole console text color.. I don't want that, not at all. I wanted to change one single specific sentence to a random color. I don't want to change console foreground/background color. All I want is one sentence into random color.
@Kristen,
What compiler (and, if relevant, IDE) are you using? Can you post the actual code that you are testing?

What does the following do on your PC? Please DON'T ADD ANY OTHER CODE to it.

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <windows.h>           
using namespace std;

int main()
{
   HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE );                              
   SetConsoleTextAttribute( h, 4 );    cout << "CALCULATOR\n";
   SetConsoleTextAttribute( h, 1 );    cout << "Made by Kristen\n\n";
   SetConsoleTextAttribute( h, 7 );    cout << "The rest of the calculator follows\n";
}


Note the quote from the Microsoft documentation for SetConsoleTextAttribute:
This function affects text written after the function call.
i.e. it cannot change console text colour written beforehand.
Last edited on
You need then so store the original color, print the text and restore the color.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <windows.h>
#include <string>

using namespace std;

enum class Color
{
  Blue = 1,
  Green,
  Red = 4,
  White = 7
};

// Based on some code from StackOverlow.com
// https://stackoverflow.com/questions/8578909/how-to-get-current-console-background-and-text-colors

BOOL ColorPrint(const Color color, string msg)
{
  HANDLE hConsole;
  WORD   currentConsoleAttr;
  CONSOLE_SCREEN_BUFFER_INFO   csbi;

  hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
  if (hConsole == INVALID_HANDLE_VALUE)
    return FALSE;
  
  if (!GetConsoleScreenBufferInfo(hConsole, &csbi))
    return FALSE;
  
  currentConsoleAttr = csbi.wAttributes;

  if(!SetConsoleTextAttribute(hConsole, static_cast<WORD>(color)))
    return FALSE;

  cout << msg;
  
  if(!SetConsoleTextAttribute(hConsole, currentConsoleAttr))
    return FALSE;

  return TRUE;
}

int main()
{
  cout << "Some text in normal colors...";
  ColorPrint(Color::Red, "\nSome error msg in Red");
  cout << "\nSome text in normal colors...";
}


https://pasteboard.co/GGQmuqn.jpg

A link to all console functions in the Win API:
https://docs.microsoft.com/en-us/windows/console/console-functions
Last edited on
Lastchance, that one worked what you showed me. Thanks a lot man! <3
Thought I'd share a simple function to do what your looking for. PS I didn't use all the colors, just what I needed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <windows.h>

using namespace std;
int Background = 0;
void Color(string color);

// use color in your output
void Color(string color){
    int colorNum;
	if (color=="White") colorNum=15;
    else if (color=="Red"   ) colorNum= 12;
    else if (color=="Cyan"  ) colorNum= 11;
    else if (color=="Gray"  ) colorNum= 8;
    else if (color=="Reset" ) colorNum= 7;
    else if (color=="Purple" ) colorNum= 5;
    else if (color=="Green" ) colorNum= 2;
    else if (color=="Blue" )  colorNum= 1;
    //Sets text color and applies background
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), (colorNum + (Background * 16)));
}

int main (int argc, char *argv[])
{
	Color("Red");  cout << "Hello, ";
	Color("White");  cout << "My ";
	Color("Blue");  cout << "name ";
	Color("Gray");  cout << "is ";
	Color("Cyan");  cout << "Sam. ";
	Color("Green");  cout << "Goodbye";
	Color("Purple");  cout << "!";
	
	Color("Reset");			
	cout << endl;
return 0;
}


PS. I found the commands here some time ago and put it in a function. Not my code, just my implementation.
Last edited on
Topic archived. No new replies allowed.