CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Dec 2010
    Posts
    8

    Read txt file into a Tuple

    Hi,
    How can I loop through a file containg values like the ones below, and stored them in a Tuple ?
    1.1, 0.1836856, 5.6
    3.3, -5.5, 43.44
    -0.38162, 6.636666E-08, 3.1
    1.01516E-07, 0.3695395, 1.5

    thank you

  2. #2
    Join Date
    Oct 2015
    Posts
    5

    Re: Read txt file into a Tuple

    Hi,

    here´s my approach

    Code:
    class ThreeTupel
    {
        public double Value1 { get; set; }
        public double Value2 { get; set; }
        public double Value3 { get; set; }
    }
    
    private static void Main(string[] args)
    {
        Run();
    }
    
    private static void Run()
    {
        var tmpTupelList = new List<ThreeTupel>();
        using (var tmpFile = new StreamReader("TextFile1.txt"))
        {
            while (!tmpFile.EndOfStream)
            {
                var tmpLine = tmpFile.ReadLine();
                tmpTupelList.Add(ParseLine(tmpLine));
            }
        }
    
        foreach (var threeTupel in tmpTupelList)
        {
            Console.WriteLine("{0}, {1}, {2}", threeTupel.Value1, threeTupel.Value2, threeTupel.Value3);
        }
    }
    
    private static ThreeTupel ParseLine(string line)
    {
        if (line == null)
            return null;
    
        var tmpValues = line.Split(',');
    
        //CultureInfo.InvariantCulture is needed for regions having a comma instead of an decimalpoint for float-numbers as systemsettings
        var tmpResult =  new ThreeTupel
        {
            Value1 = double.Parse(tmpValues[0], NumberStyles.Float, CultureInfo.InvariantCulture),
            Value2 = double.Parse(tmpValues[1], NumberStyles.Float, CultureInfo.InvariantCulture),
            Value3 = double.Parse(tmpValues[2], NumberStyles.Float, CultureInfo.InvariantCulture)
        };
    
        return tmpResult;
    }

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured