Easiest way to colour text in C/C++ DOS?

3.6k views Asked by At

I made a basic snake game in a DOS enviroment using turbo C++ 3.0, and I'm quite a rookie myself. I've been looking for a while for a very simple and perhaps rudimentary way of making text of different colors in a DOS window. I'm not looking for complicated ways of coloring text. Most programs I'm writing are extremely simple and basic, and a complicated code to colour text that's larger than the program itself would just be confusing and ineffective.

My question is, what is the simplest way of coloring text in a DOS console in BOTH language, C and C++?

4

There are 4 answers

0
Alexey Frunze On BEST ANSWER

You can use Turbo C/C++'s-only (that is, non-standard) functions textcolor(), textbackground() and textattr() together with cprintf(), cputs() and putch(). See their description in the IDE's help, they're all in conio.h.

0
AudioBubble On

If you enable ansi.sys, you can use ansi escape sequences.

I assume you're using DOS on Windows, as you refer to a "DOS window", so you need to enable ansi.sys before you can use it.

Turbo C++ 3.0 doesn't come with Windows headers or libraries, so you won't be able to use the Console API.

0
arx On

Are you actually using DOS (e.g. DOSBox or DOS on Win 9x)?

If so, ANSI.SYS is very straightforward to use. You just precede your text with control codes that set the colour.

If not, (i.e. you're actually using a command-prompt on Windows) then use SetConsoleTextAttribute to set the foreground and background colours.

And I just remembered, 32-bit versions of Windows still support command.com and this can load ANSI.SYS.

0
wallyk On

If you write directly to the video text buffer, each character cell onscreen corresponds to a pair of bytes, one is the character to display, the other is its colors. See http://en.wikipedia.org/wiki/VGA_compatible_text_mode

At first, it might seem a bit daunting, but it is actually quite straightforward. It is just a bit unfamiliar. Using the ANSI escape sequences requires generating quite a bit of output whereas the text buffer is one 16-bit word per character.

Not that it matters anymore, but on vintage era hardware it was necessary to write to the text buffer to get responsive changes. Going through the ANSI interface took a visibly significant amount of time.