On Tuesday, 11 March 2014 at 05:37:25 UTC, Timothee Cour wrote:You could simply create an sink that forwards to stdout, while keeping state:
void writelnIfNotEmpty(T)(T a){
auto file_pos=get_filepos(stdin);
write(a);
if(get_filepos(stdin)!=file_pos)
writeln;
}
//----
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!