writeln if not empty
Timothee Cour
thelastmammoth at gmail.com
Tue Mar 11 19:56:45 PDT 2014
Thanks! your solution is more robust (minus some caveats i mentioned) and
also trivially extends to variadics.
On Tue, Mar 11, 2014 at 2:07 PM, monarch_dodra <monarchdodra at gmail.com>wrote:
> 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!
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20140311/593b2a65/attachment.html>
More information about the Digitalmars-d-learn
mailing list