Can I output strings using core.stdc.stdio?

Godnyx rempas at tutanota.com
Wed Dec 23 12:23:17 UTC 2020


On Wednesday, 23 December 2020 at 09:50:03 UTC, Ali Çehreli wrote:
> On 12/23/20 1:06 AM, Godnyx wrote:
>
> >      for (ulong i = 0; i < args.length; i++) {
> >          if (typeof(args[i]).stringof == "string")
> >              printf("%s\n", args[i].toStringz);
> >      }
>
> I replaced for with foreach and it worked (and I passed 
> "prompt"). static foreach would work as well.
>
> import core.stdc.stdio : printf;
> import std.string : toStringz;
>
> void put(A...)(string prompt, A args) {
>     foreach (arg; args) {
>         if (typeof(arg).stringof == "string")
>             printf("%s\n", arg.toStringz);
>     }
> }
>
> void main() {
>     string h = "World!";
>     string w = "World!";
>     put("prompt", h, w);
> }
>
> But it can get better: you don't want to compare typeof with 
> "string" at run time. Instead, there shouldn't be any code 
> generated for the non-string cases. Enter 'static if' and the 
> 'is' expression to feel better. :)
>
> import core.stdc.stdio : printf;
> import std.string : toStringz;
>
> void put(A...)(string prompt, A args) {
>   static foreach (arg; args) {
>     static if (is (typeof(arg) == string)) {
>       printf("%s\n", arg.toStringz);
>     }
>   }
> }
>
> void main() {
>   string h = "World!";
>   string w = "World!";
>   put("prompt", h, w);
> }
>
> Ali

Probably the best solution! It also let's me use types other than 
string! Example: put("Prompt:", "Hello, my age is: ", 19, true); 
tho still I can't print anything. This is the code:

void put(A...)(string prompt, A args) {
     static foreach (ulong i; 0..args.length) {
         static if (is(typeof(arg) == string))
             printf("%s\n", args[i].toStringz);
         static if (is(typeof(arg) == int))
             printf("%i\n", args[i]);
         static if (is(typeof(arg) == bool)) {
             if (arg)
                 printf("true");
             else
                 printf("false");
         }
     }
}

void main() {
     put("Prompt:", "Hello, my age is: ", 19, true);
}

Any ideas?


More information about the Digitalmars-d-learn mailing list