Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

printf Example

Part of TutorialFundamentals

You should prefer using writef, but in case you want to use printf you should be aware of a few corner cases. Here's the classic printf example (you have to import core.stdc.stdio to use printf):

import core.stdc.stdio;

void main()
{
    printf("Hello World\n");
}

Here's the equivalent code using writef:

import std.stdio;

void main()
{
    writef("Hello World\n");
}

When using the %s formatting token with printf you must be careful to use it with the embedded length qualifier: %.*s. This is because the difference between C and D is that C strings are zero-terminated character arrays referenced by an address, but in D they are a dynamic array object which is really an eight-byte structure containing a length and pointer:

import core.stdc.stdio;

void main()
{
    string mystring = "hello";
    printf("%.*s\n", mystring);
    //~ printf("%s\n", mystring);  // <<-- This would fail in runtime.
}

The printf's %.*s will print until the length is reached or an embedded 0 is encountered, so D strings with embedded 0's will only print up to the first 0.

When you absolutely must pass a string variable to a C function (such as printf, or maybe an external c function), you can use the std.string.toStringz function. However the string you pass to toStringz should not have an embedded zero, or you will have problems:

import core.stdc.stdio;
import std.string;

void main()
{
    string mystring = "hi\n";
    string oops = "I have an embedded \0, oops!";
    
    printf("%s", toStringz("Hello, world!\n"));
    printf("%s", toStringz(mystring));
    printf("%s", toStringz(oops));
}

Output:

Hello, world!
hi
I have an embedded