reading from file
bluecat via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Dec 13 08:19:42 PST 2016
On Tuesday, 13 December 2016 at 15:42:16 UTC, Namal wrote:
> Hello, comming from C++, I find it hard to remember and
> understand how reading from file should be done in D.
> Especially since I am not very good in functional programming.
> So I have a file which looks like this:
>
> 1,2,3,4
> 5,6,7,8
> 9,11,11,12
>
> and so on
>
> How could I read it row by row and create an array accordingly
> without reading the comma?
import std.stdio;
import std.string: strip;
import std.algorithm: splitter, each;
import std.array: array;
void main() {
//prepare variables
File file = File("new.txt", "r");
string[] arr;
//read file
while(!file.eof) {
file
.readln
.strip
.splitter(",")
.array
.each!(n => arr ~= n);
}
arr.writeln;
}
//here is my attempt. copy, paste, run the program to see if it
is what you want.
//feel free to ask any questions about my code, it isn't perfect
but it works.
More information about the Digitalmars-d-learn
mailing list