Sum informations in file....

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Nov 24 11:40:05 PST 2014


On 11/24/2014 11:04 AM, Suliman wrote:

 > I can't understand why foreach loop produce every line by line, while
 > it's fuctional analog print lines on one string:
 >
 > foreach(f; file.byLine())
 > {
 >      writeln(f);

f is a char[] and writeln prints all strings as their contents i.e. 
"first string" is printed as

first string

 > }
 >
 > auto file = File("foo.txt","r");
 > file
 > .byLine()
 > .writeln;

In that case the first three lines make a range object. By default, 
writeln prints ranges as if they are arrays. For this example, the range 
is a range of strings, so it prints it as

[ "first string" ]

writefln gives us more power:

     auto content = File("foo.txt","r").byLine();
     writefln("%-(%s\n%)", content);

Per-element formatting is specified within %( and %). So, each element 
would be printed with "%s\n" format. Notes:

1) The dash in %-( means "do not print the double-quotes for strings"

2) Everything after %s in the per-element formatting is taken as element 
delimiter and writefln does not print the delimiters are not printed for 
the last element. One may need to use %| to specify the actual delimiters.

Here is the spec:

   http://dlang.org/phobos/std_format.html#.formattedWrite

Here is my rewording:

   http://ddili.org/ders/d.en/formatted_output.html

Ali



More information about the Digitalmars-d-learn mailing list