www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 12284] New: Formatting for C strings too

https://d.puremagic.com/issues/show_bug.cgi?id=12284

           Summary: Formatting for C strings too
           Product: D
           Version: D2
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: enhancement
          Priority: P2
         Component: Phobos
        AssignedTo: nobody puremagic.com
        ReportedBy: bearophile_hugs eml.cc


--- Comment #0 from bearophile_hugs eml.cc 2014-03-02 03:19:13 PST ---
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.

-- 
Configure issuemail: https://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
Mar 02 2014