Writing colored output to the console
The writefln
function has a lot of formatting options for strings, but they always come out with the same default color. How can we create colored text output in D?
Getting ready
Download terminal.d
from my Github repository to your project's directory.
How to do it…
Let's write colored output to the console by executing the following steps:
Import
terminal
.Create an instance of
Terminal
with a linear output type.Set the foreground and background color with the
terminal.color
method.Write text with the
terminal.write
,terminal.writeln
,terminal.writef
, orterminal.writefln
functions. They work the same way as the homonym functions instd.stdio
.You can flush output with
terminal.flush()
if it isn't done soon enough automatically.Compile the program and
terminal.d
together withdmd yourfile.d terminal.d
.
The following is the code:
import terminal; void main() { auto terminal = Terminal(ConsoleOutputType.linear); terminal.color(Color.green, Color.red); ...