1.

How Do I Get Printf() To Work With Strings?

Answer»

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.

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.



Discussion

No Comment Found