csvReader: how to read only selected columns while the class Layout has extra field?

mw mingwu at gmail.com
Sun Oct 2 19:46:00 UTC 2022


Hi,

I'm following the example on

https://dlang.org/phobos/std_csv.html

```
     class Layout
     {
         int value;
         double other;
         string name;
         int extra_field;  // un-comment to see the error
     }

void main()
{
     import std.csv;
     import std.stdio: write, writeln, writef, writefln;
     import std.algorithm.comparison : equal;
     string text = "a,b,c\nHello,65,2.5\nWorld,123,7.5";

     auto records =
         text.csvReader!Layout(["b","c","a"]);  // Read only these 
column
     foreach (r; records) writeln(r.name);
}
```

This works fine so far, but if I un-comment the extra_field line, 
I got runtime error:

```
core.exception.ArrayIndexError@/dlang/dmd/linux/bin64/../../src/phobos/std/csv.d(1209): index [3] is out of bounds for array of length 3
----------------
??:? _d_arraybounds_indexp [0x5565b4b974d1]
/dlang/dmd/linux/bin64/../../src/phobos/std/csv.d:1209 pure @safe 
void std.csv.CsvReader!(onlineapp.Layout, 1, immutable(char)[], 
dchar, immutable(char)[][]).CsvReader.prime() [0x5565b4b73ed2]
/dlang/dmd/linux/bin64/../../src/phobos/std/csv.d:1154 pure @safe 
void std.csv.CsvReader!(onlineapp.Layout, 1, immutable(char)[], 
dchar, immutable(char)[][]).CsvReader.popFront() [0x5565b4b73c80]
/dlang/dmd/linux/bin64/../../src/phobos/std/csv.d:1069 pure ref 
@safe std.csv.CsvReader!(onlineapp.Layout, 1, immutable(char)[], 
dchar, immutable(char)[][]).CsvReader 
std.csv.CsvReader!(onlineapp.Layout, 1, immutable(char)[], dchar, 
immutable(char)[][]).CsvReader.__ctor(immutable(char)[], 
immutable(char)[][], dchar, dchar, bool) [0x5565b4b73ae8]
/dlang/dmd/linux/bin64/../../src/phobos/std/csv.d:366 pure @safe 
std.csv.CsvReader!(onlineapp.Layout, 1, immutable(char)[], dchar, 
immutable(char)[][]).CsvReader 
std.csv.csvReader!(onlineapp.Layout, 1, immutable(char)[], 
immutable(char)[][], char).csvReader(immutable(char)[], 
immutable(char)[][], char, char, bool) [0x5565b4b735f3]
./onlineapp.d:18 _Dmain [0x5565b4b72ca4]
```

I'm just wondering how to work-around this?

Thanks.


More information about the Digitalmars-d-learn mailing list