A Beginner's Guide to D/The Basics/Basic Output

One of the most basic operations you can do with a program is to print out some text in a console window (sometimes also called DOS-box). Even if you later only use graphical environments to show nice windows on the screen, writing to a console is always helpful to tell the programmer what the program is currently doing so he/she can check if it does the right thing and can find bugs (mistakes in the source code) in the program.

Very versatile functions to write something to the console are writef and writefln.

First of all, these functions are placed in a separate module named "std.stdio", so you have to import it, as you have learned in Introduction to Modules.

Here is a very simple program that only writes a single string literal to the console:

If you compile and run it, you will see the text

Hello, world!

on the screen.

As you have learned in Types and Math you can use escape sequences, also in writefln:

Output:

Hello, world!

The difference between writef and writefln is only that the latter automatically appends a "\n" after the output. Everywhere where you use writefln you can instead use writef and append the newline yourself, this is just less practical.

Output:

<b>Hello, this is allon one line Another line</b>

There was no space after the "all" in the source, therefore there isn't a space in the output either.

It is a good idea to always have a newline after the last output of a program.

Printing Variables
<tt>writef</tt> and <tt>writefln</tt> are useful for more than just printing string literals. They can print any combination of variables with one of the basic numeric types or string types or arrays of such items.

Output:

<b>8 [1,2,4,3] 3.1415 Integer 5 plus double 3.1415 gives 8.1415</b>

As you can see in the last output of the example, you can also write multiple expressions as a comma-separated list of parameters to <tt>writef</tt> and <tt>writefln</tt>.

This last line can also be written in another way with a format string which is more common to C programmers. A format string is a single string containing some fixed text and placeholders for data which is contained in variables or expressions. The values which must be placed in the format string are appended as additional parameters after the format string itself.

A placeholder in the format string begins always with a percent sign % and ends with a letter which defines how to output the value (the format character). For some letters there can be additional characters between percent sign and letter to control the output more precisely (especially for numbers).

The default all-purpose format character is the 's' which can be used everywhere. So the line above can be rewritten as

with exactly the same output.

[TODO: More details] (stub)