0 votes
in D Programming by
How Do I Get Printf() To Work With Strings?

1 Answer

0 votes
by
In C, the normal way to printf a string is to use the %s format:

char s[8];

strcpy(s, "foo");

printf("string = '%s'n", s);

Attempting this in D, as in:

char[] s;

s = "foo";

printf("string = '$(B %s)'n", s);

usually results in garbage being printed, or an access violation. The cause is that in C, strings are terminated by a 0 character. The %s format prints until a 0 is encountered. In D, strings are not 0 terminated, the size is determined by a separate length value. So, strings are printf'd using the %.*s format:

char[] s;

s = "foo";

printf("string = '$(B %.*s)'n", s);

which will behave as expected. Remember, though, that printf's %.*s will print until the length is reached or a 0 is encountered, so D strings with embedded 0's will only print up to the first 0.

Of course, the easier solution is just use std.stdio.writefln which works correctly with D strings.

Related questions

0 votes
asked Mar 5, 2021 in D Programming by SakshiSharma
0 votes
asked Aug 9, 2021 in AWS Access Management by rajeshsharma
...