writeln if not empty

monarch_dodra monarchdodra at gmail.com
Tue Mar 11 14:07:51 PDT 2014


On Tuesday, 11 March 2014 at 05:37:25 UTC, Timothee Cour wrote:
> void writelnIfNotEmpty(T)(T a){
> auto file_pos=get_filepos(stdin);
> write(a);
> if(get_filepos(stdin)!=file_pos)
> writeln;
> }

You could simply create an sink that forwards to stdout, while 
keeping state:

//----
import std.stdio, std.format;

bool writelnIfNotEmpty(T)(T a)
{
     bool written = false;
     void checkWriter(in char[] s)
     {
         if (s.length)
         {
             written = true;
             write(s);
         }
     }
     formattedWrite(&checkWriter, "%s", a);
     if (written)
     {
         writeln();
         return true;
     }
     return false;
}

void main()
{
     writelnIfNotEmpty(1);
     writelnIfNotEmpty("");
     writelnIfNotEmpty(2);
}
//----

This prints:
//----
1
2
//----

Also, this didn't work up until a few releases ago. I am really 
really happy to see code like this finally "just work". yay!


More information about the Digitalmars-d-learn mailing list