Creating Structs/Classes at runtime?

Ali Çehreli acehreli at yahoo.com
Sun Feb 17 21:26:38 PST 2013


On 02/17/2013 04:44 PM, Brian Brady wrote:

 > 1) my full csv is 4000 variables wide, and I really don't want to
 > declare each variable in the struct (I've created a smaller one to test)

Looking at the sample file you provide, what you call "variables" look 
like data points.

 > 2) what if I wanted to read in different csvs of different sizes, I
 > don't want to have to change my program each time?

Then you need something other than a CSV reader. Ordinarily, records in 
a CSV files have a known number of fields.

 > After much googling, I thought I found something on RosettaCode that
 > would do what I wanted
 > 
(http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime#D) 

 >
 > but when I try to use it, it doesn't work. (Its actually adding to a
 > class, which may be better than a struct in this instance, but
 > regardless, it doesn't work)

That is not a natural idiom for D and I don't think it is needed here. :)

 > The csv I would eventually like to read in is of the form:
 >
 > test1,303,-140,-166,-317,-310,414,-157,-360,-120,-89
 > test10,-1,70,-57,-101,112,137,-134,9,195,86
 > test100,367,78,-417,123,220,-234,-170,236,-218,-351
 > test1000,309,-178,-674,-202,514,218,-165,76,-82,-328
 > test10000,-131,142,6,-143,80,46,29,48,-84,-113

What I see there is a label and a number of integers. Here is a simple 
parser that takes advantage of the %( and %) grouping format specifiers:

import std.stdio;
import std.format;

struct Data
{
     string label;
     int[] values;
}

int main(string[] args)
{
     if (args.length != 2) {
         stderr.writefln("Usage: %s <input-file-name>", args[0]);
         return 1;
     }

     auto file = File(args[1], "r");

     Data[] data;

     foreach (line; file.byLine) {
         string label;
         int[] values;
         formattedRead(line, "%s,%(%s,%)", &label, &values);
         data ~= Data(label, values);
     }

     writeln(data);

     return 0;
}

Ali

-- 
D Programming Language Tutorial: http://ddili.org/ders/d.en/index.html



More information about the Digitalmars-d-learn mailing list