reading file byLine
cym13 via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Sep 2 08:04:09 PDT 2015
On Wednesday, 2 September 2015 at 13:46:54 UTC, Namal wrote:
> Thx, cym. I have a question about a D strings though. In c++ I
> would just reuse the string buffer with the "=" how can I clear
> the string after i store a line in the buffer and do something
> with it. I also tried to append a line to an array of strings
> but it failed because the line is a char?
In D you can do as in C++:
buffer = ""; // or a brand new string
You can also reset a variable to its initial state (what you
would hav had if you hadn't initialized it) using:
buffer.init();
When reading files the default type you get is dchar[]. There are
different kind of strings in D, you way want to check
http://dlang.org/arrays.html#strings . If you want to append to
an array of strings, simply convert your line to type string:
import std.conv;
import std.stdio;
void main() {
string[] buffer;
foreach (line ; File("test.txt").byLine)
buffer ~= line.to!string; // <- Here is the magic
writeln(buffer);
}
More information about the Digitalmars-d-learn
mailing list