Printing a C "string" with write(f)ln

Jakob Ovrum via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Feb 9 04:50:27 PST 2016


On Tuesday, 9 February 2016 at 12:46:59 UTC, Whirlpool wrote:
> Hello,
>
> When you are using a C function (from an external library) that 
> returns a pointer on char which is the beginning of a string (I 
> know that C does not have a string type, that they are just 
> arrays of chars ended by '\0'), is there a simple way to print 
> that string with D's write(f)ln, should I use C's printf, or 
> something else ? What is the best way ? Because if I do
> writefln("... %s", *pString);
> it only displays the first character of the string, the value 
> that pString points to
>
> Thanks

writefln et al sensibly does *not* assume that a pointer to char 
is a C string, for memory safety purposes.

Print the result of std.string.fromStringz[1] instead:

writeln(fromStringz(pString));
writefln("%s", fromStringz(pString));

[1] http://dlang.org/phobos/std_string#fromStringz


More information about the Digitalmars-d-learn mailing list