Maxpm
Maxpm

Reputation: 25642

What is the preferred console output method in modern D?

Most of the D language tutorials I've seen use printf to output text to the console, but that can't be right. I know that D provides direct access to the C/C++ libraries, but shouldn't D's console output function be used instead? What is the preferred method for outputting text (formatted or otherwise) to a console window?

Upvotes: 6

Views: 710

Answers (2)

BCS
BCS

Reputation: 78683

The use of printf is mostly historical. It has been used because it is declared in one of the modules that is automatically imported and that make the examples shorter. Also, the author of D wrote many of the examples and IIRC, while debugging the compiler he prefers printf over writef because there is less to go wrong. That plus muscle memory results in printf leaking into examples.

Upvotes: 1

GManNickG
GManNickG

Reputation: 504343

Within the module std.stdio, you'll find write and friends: writeln, writef, and writefln.


write just takes each argument, converts it to a string, and outputs it:

import std.stdio;

void main()
{
    write(5, " <- that's five"); // prints: 5 <- that's five
}

writef treats the first string as a format-specifier (much like C's printf), and uses it to format the remaining arguments:

import std.stdio;

void main()
{
    writef("%d %s", 5, "<- that's five"); // prints: 5 <- that's five
}

The versions ending with "ln" are equivalent to the version without it, but also append a newline at the end of printing. All versions are type-safe (and therefore extensible).

Upvotes: 9

Related Questions