Read csv data into a struct

Ali Çehreli acehreli at yahoo.com
Fri Mar 2 14:50:25 PST 2012


On 03/02/2012 02:01 PM, Yao Gomez wrote:
> On Friday, 2 March 2012 at 21:50:12 UTC, tjb wrote:
>> Woops. I have a mistake in the code. Should be:
>>
>> import std.stdio : writeln;
>> import std.stream;
>>
>> void main() {
>> auto fin = new File("temp.csv");
>> char[] line;
>>
>> int count;
>> while(!fin.eof()) {
>> line = fin.readLine();
>> writeln(line);
>> }
>> }
>>
>> Thanks!
>>
>> TJB
>
> Check this module: http://dlang.org/phobos/std_csv.html
>
> It can parse the CVS file content into a custom class/struct.

Thanks, that's very helpful.

1) I have modified the example from that module's documentation to take 
advantage of tuple expansions in foreach loops. Notice firstName, etc. 
instead of record[0], record[1], etc. (This is a relatively new feature.)

2) I've also used a struct instead of a tuple. (This is what TJB wants.)

3) And finally created an array of objects.

import std.csv;
import std.stdio;
import std.typecons;
import std.array;

struct Worker
{
     string firstName;
     string occupation;
     int amount;
}

void main()
{
     auto text = "Joe,Carpenter,300000\nFred,Blacksmith,400000\r\n";

     /* Take advantage of tuple expansion in foreach loops */
     foreach(firstName, occupation, amount;
             csvReader!(Tuple!(string,string,int))(text))
     {
         writefln("%s works as a %s and earns $%d per year",
                  firstName, occupation, amount);
     }

     /* Use a struct instead of a tuple */
     foreach (worker; csvReader!Worker(text)) {
         writeln("Worker in foreach: ", worker);
     }

     /* Make an array of Workers directly from the data */
     Worker[] workers = array(csvReader!Worker(text));
     writeln("Workers in array: ", workers);
}

Ali


More information about the Digitalmars-d-learn mailing list