Comment #0 by bearophile_hugs — 2014-03-02T03:19:13Z
This shows the slightly inconsistent behavour of D printing functions, text() prints a pointer if given a void* and it prints a string if given a char*:
void main() {
import std.stdio, std.conv, std.string;
auto p = "test".ptr;
printf("%s\n", p);
writef("%s\n", p);
format("%s", p).writeln;
p.text.writeln;
text(cast(void*)p).writeln;
}
Output:
test
4240A0
4240A0
test
4240A0
There are situations when I have 0-terminated C-style stings, sometimes even inside arrays, ranges or associative arrays, and I'd like to print them:
immutable(char)* str = ...;
const(char)*[] cStrings = ...;
uint[immutable(char)*] frequencies = ...;
In such cases I can convert them to D strings using the text() function, or I can use printf:
printf("%s\n", str);
cStrings.map!text.writeln;
foreach (key, val; frequencies)
writeln(key.test, " ", val);
But I'd like format/writeln to be able to handle 0-terminated C strings with a specific format string:
writefln("%S", str);
writefln("[%-(%S, %)]", cStrings);
writefln("%-(%S %d\n%)", frequencies);
It could work even for this case:
immutable(dchar)* dstr = "test"d.ptr;
writefln("%S", dstr);
Some of the disadvantages of this idea:
- All other formatting work similarly in upper and lower case, while here "s" formats to strings, and "S" formats 0-terminated strings.
- 0-terminated strings are not very safe, if you forget to terminate them you will keep printing for a while.
- In D programs most times you use normal D strings. Even when you have to deal with C strings to interact with C libraries, you often convert the C strings to D strings as soon as possible. So C style strings are uncommon in D code.
Comment #1 by robert.schadek — 2024-12-01T16:20:19Z