best replacement for - cout << "hello D" << endl; ?

Jarrett Billingsley kb3ctd2 at yahoo.com
Tue Jul 10 19:56:39 PDT 2007


"Bruce Adams" <tortoise_74 at no.spam.ya.hoo.co.uk> wrote in message 
news:f71fdt$rfp$1 at digitalmars.com...
> Hi,
>   The biggest single problem with D is that its a very very bad search 
> term for google. I usually add phobos but that doesn't always help.

The accepted search term is becoming "D programming language" or just "D 
programming".  Walter's been pushing that for a while now, and suggests that 
D sites include the phrase at least once.

Keep in mind that "C" is a pretty terrible search term too ;)

>   I'm trying to find the 'best' replacement for C++ streaming I/O.
> I dislike C style format strings because of the type safety issue and run 
> time interpretation issues. I'm pretty sure D works around this using a 
> typeinfo array but I keep losing the function. I understand that writefln 
> is now favoured over printf 
> (http://www.prowiki.org/wiki4d/wiki.cgi?HowTo/printf).

Type safety is not an issue with Phobos' formatting strings; they just 
happen to look like printf's formatting.  In fact you can just use %s for 
everything, and it'll figure it all out at runtime.  However if runtime type 
identification for formatted printing is not what you're looking for, you 
won't find any alternative in Phobos.

For that, there's Tango (http://www.dsource.org/projects/Tango), an 
alternative community-driven standard library for D which is quickly gaining 
popularity.  One of Tango's claims to fame is its much more flexible and 
powerful IO framework.  I'm not sure if it still provides the C++ style << 
and >> for writing and reading (they may have been removed), but it uses the 
same basic idea of chained overloaded operator calls, but using the call 
operator instead of the shift operators.  For example, here is a use of the 
Stdout object, similar to C++'s cout:

import tango.io.Stdout;

void main()
{
    int x = 6;
    Stdout("X is: ")(x).newline;
}

Like in C++ streams, each item is outputted separately, and uses its own 
method overload, avoiding runtime type identification.  Objects which read 
use the same syntax (called "whisper" for reasons I don't entirely 
understand ;) ).

Of course there's also C#-style formatted printing:

Stdout.formatln("X is: {}", x);

Which, like Phobos' format() family of function (including writefln()), uses 
RTTI to correctly output the formatted values.  This is also necessary for 
any custom formatting, such as outputting hex integers or field widths, 
since there is no analogue to the i.e. ios::hex as in C++ for the chained 
output method. 




More information about the Digitalmars-d-learn mailing list