www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - tuples from text file

reply codephantom <me noyb.com> writes:
so I have a text file containing 3 lines(e.g):

5, "hello", 4.3
"hello", 4.3
"hello", "world", 1, 2, 3, 5.5

Now I want to create tuples from each line.

However, (using line 1 as example), I get:

Tuple!string("5, \"hello\", 4.3")

but I really want:

Tuple!(int, string, double)(5, "hello", 4.3)

I know why - because a line is a string.

But anyone got an idea on how to extract the string into separate 
elements that can be correctly 'tuple'd" according to the type of 
each element?

// -------
module test;

import std.stdio : writeln;
import std.typecons;
import std.string;
import std.file : readText;

void main()
{
     string myFile= "tuples.txt"; // contains 3 lines as per 
examples above
     auto lineArr = readText(myFile).splitLines();
     writeln( tuple(lineArr[0]) ); // doesn't give me the tuple I 
want.
}

//-----------
Dec 19 2017
parent Steven Schveighoffer <schveiguy yahoo.com> writes:
On 12/19/17 7:47 PM, codephantom wrote:
 so I have a text file containing 3 lines(e.g):
 
 5, "hello", 4.3
 "hello", 4.3
 "hello", "world", 1, 2, 3, 5.5
 
 Now I want to create tuples from each line.
 
 However, (using line 1 as example), I get:
 
 Tuple!string("5, \"hello\", 4.3")
 
 but I really want:
 
 Tuple!(int, string, double)(5, "hello", 4.3)
 
 I know why - because a line is a string.
 
 But anyone got an idea on how to extract the string into separate 
 elements that can be correctly 'tuple'd" according to the type of each 
 element?
Well, you need to know at compile time the types you are expecting. Then you just parse them out. You can't decide tuples at runtime. -Steve
Dec 19 2017