coloring a single word in a text

how do i color a single word in a text?
lets say if i have the text: "hello i'm Bob" i want to color only "i'm" in red.
i know that:

HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute( handle, Color );

should solve the problem but i don't know how to set a fixed range to be colored instead of the whole text.
SetConsoleTextAttribute() modifies the color of all text to be written.

So, to make just part of the text red, change it to red before writing the word and change it back to the original color after.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>

void setcolor( unsigned char color )
{
  SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ), color );
}

int main()
{
  setcolor( 0x07 );  // Initial color for program

  std::cout << "Hello ";
  setcolor( 0x0C );
  std::cout << "I'm";
  setcolor( 0x07 );
  std::cout << " Bob.\n";
}

Be aware, this is a simple example. You should typically use GetConsoleScreenBufferInfo() to learn the current color, then initialize it to the color your application will use by default, and restore the original color before your application terminates.

Hope this helps.
thanks this is helpful! do you know by any chance how to change a words color only when the cursor is fixed on the words position ?
i use: void gotoxy(int x, int y)
{
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
COORD position = { x, y };

SetConsoleCursorPosition(hStdout, position);
}

(function to change the cursors position)

now if i have a word on (16,2) coordinates and the cursor is on the same word it should be colored red if the cursor doesn't point to that position it should be the default white color.
It is (much) more trouble than it is worth.

What exactly are you trying to accomplish?
You might be better of using the PDCurses library.
+globaltourist, i think you cant while you are on an console application.

+Duoas, he wants simply to color an word :), i think he wants for console application, your exemple is the best also, thank you, i need that :D
closed account (E0p9LyTq)
An old (2013) cplusplus article for adding color to console apps using WinAPI:

http://www.cplusplus.com/articles/Eyhv0pDG/

I have used it in the past and find it to be easy to use.
thanks everyone for help i have done what i needed without coloring by using cursor position and moving pointers on options but i learned a new thing from your comments!
Topic archived. No new replies allowed.