Changes between Version 1 and Version 2 of PrintfExample/D2
- Timestamp:
- 09/09/10 00:42:17 (14 years ago)
Legend:
- Unmodified
- Added
- Removed
- Modified
-
PrintfExample/D2
v1 v2 3 3 ''Part of'' TutorialFundamentals 4 4 5 It's better to use writef these days, but here's a printf example just for the heck of it. 5 You should prefer using writef, but in case you want to use printf you should be aware of a few corner cases. 6 Here's the classic printf example (you have to import ''core.stdc.stdio'' to use printf): 6 7 7 8 {{{ 9 10 import core.stdc.stdio; 10 11 11 int main(string[] args)12 void main() 12 13 { 13 14 printf("Hello World\n"); 14 return 0;15 15 } 16 16 }}} 17 17 18 Here's the same thing withwritef:18 Here's the equivalent code using writef: 19 19 20 20 {{{ 22 22 import std.stdio; 23 23 24 int main(string[] args)24 void main() 25 25 { 26 26 writef("Hello World\n"); 27 return 0;28 27 } 29 28 }}} 30 29 31 However when using the ''%s'' formatting token with printf you must be careful to use it with the embedded length qualifier. This is because the difference between C++ and D is that C++ strings are zero-terminated character arrays referenced by an address, but in D they are a dynamic array object which is really an eight-byte structure containing length and pointer. 32 33 Note however that a string '''literal''' in D ( for example, the first argument to printf ) is a null-terminated string. 30 When using the '''%s''' formatting token with printf you must be careful to use it with the embedded length qualifier: '''%.*s'''. This is because the difference between C and D is that C strings are zero-terminated character arrays referenced by an address, but in D they are a dynamic array object which is really an eight-byte structure containing a length and pointer: 34 31 35 32 {{{ 37 34 import core.stdc.stdio; 38 35 39 int main(string[] args)36 void main() 40 37 { 41 printf("%.*s\n", args[0]);42 //~ printf("%s\n", args[0]); // <<-- This will fail.43 return 0;38 string mystring = "hello"; 39 printf("%.*s\n", mystring); 40 //~ printf("%s\n", mystring); // <<-- This would fail in runtime. 44 41 } 45 42 }}} 43 44 The printf's '''%.*s''' will print until the length is reached or an embedded 0 is encountered, so D strings with embedded 0's will only print up to the first 0. 45 46 When you absolutely must pass a string variable to a C function (such as printf, or maybe an external c function), you can use the '''std.string.toStringz''' function. However the string you pass to ''toStringz'' should not have an embedded zero, or you will have problems: 47 48 {{{ 49 #!d 50 import core.stdc.stdio; 51 import std.string; 52 53 void main() 54 { 55 string mystring = "hi\n"; 56 string oops = "I have an embedded \0, oops!"; 57 58 printf("%s", toStringz("Hello, world!\n")); 59 printf("%s", toStringz(mystring)); 60 printf("%s", toStringz(oops)); 61 } 62 }}} 63 64 Output: 65 {{{ 66 Hello, world! 67 hi 68 I have an embedded 69 }}}