On Tuesday, 9 January 2018 at 19:05:48 UTC, thedeemon wrote:
On Tuesday, 9 January 2018 at 18:09:58 UTC, Vino wrote:
It is possible to store struct in a array ans use the same in csvReader

Sure, you can just pass the type of your struct to csvReader:

Array!T1 T1s;
reader(fName, T1s); // pass the array Type as a function parameter

First you write a template function that takes an array of some generic type and fills it with records from CSV file:

void readData(DataType)(string fname, ref Array!DataType arr) {
    foreach (record; fname.readText.csvReader!DataType('\t')) {
        arr ~= record;
    }
}

Then you can use it in your main program with different types:

struct S1 { string name; string value; int other; }
struct S2 { int a; string b; }

void main () {
    ...
    if (someCondition) {
        Array!S1 arr1;
        readData("data1.csv", arr1);
    } else {
        Array!S2 arr2;
        readData("data2.csv", arr2);
    }
}

A little advice. Kindly pause and spend an evening reading this book:
http://ddili.org/ders/d.en/

Currently your code pieces look like a soup produced by someone who still confuses variables and types, and lacks basic programming skills. Read the book, don't rush with writing broken code.

Hi Deemon,

I agree that my code is broken code and I am a Newbie in the world of programming, the confusion begin when i started writing the second module, and now i was able to find the issue, and the real requirement. The requirement is as below.

Program: The below program works.
auto reader(MyStruct) (File fname, auto ref MyStruct st) {
alias ColumnTypes = AliasSeq!(MyStruct);
foreach (record; fname.byLineCopy().joiner("\n").csvReader!(Tuple!ColumnTypes)(null)) {
writeln(record[0], record[1], record[2]);
}

void main () {
auto fname = File("C:\\Users\\bheev1\\Desktop\\Current\\Script\\Others\\Table2.csv");
auto Table = baseName(stripExtension(fname));
struct S1 { string Name; string Country; int Age; }
S1 Table1s;
reader(File(fname), join([Table, "1s"]));
}

The requirement is as below
The function reader should store the data in column wise Array and return the same.

Array!<Type has to be taken from ColumnTypes < Name of the array has to be taken from the header data as the CSV file has header Name, Country, Age using records.header)
e.g
Array!string Name; (records.header[0]);
Array!string Country;(records.header[1]);
Array!string Age;(records.header[2]);

and return the above arrays

From,
Vino.B



Reply via email to