How to read numbers from a txt file in C #? [closed]

1

This is an example file:

2
0.03159527 0.1990048 0.9794891
0.02173799 0.9969404 0.07508247

The first number indicates how many lines are, for each line there are always three numbers

I tried to do something like this:

    Vector3[] Load()
{
    StreamReader entrada = new StreamReader ("gestos_saida.txt");

    int size = entrada.Read ();
    Vector3[] v = new Vector3[size];
    for (int i = 0; i < size; i++)
    {
        float x, y, z;
        x = entrada.Read ();
        y = entrada.Read ();
        z = entrada.Read ();
        v[i] = new Vector3 (x, y, z);
    }

    entrada.Close ();
    return v;
}

But the read numbers do not match the file, how can I read those numbers without having to use a ReadLine() and then break the string ?

    
asked by anonymous 21.07.2017 / 22:40

2 answers

3

You can not, it has to be manual. need to read s lines, break the data and convert them. I considered that the file will always be well formatted and with correct data. Something like this:

using System;
using static System.Console;
using System.IO;

public class Program {
    public static void Main(string[] args) {
        var texto = "2\n0.03159527 0.1990048 0.9794891\n0.02173799 0.9969404 0.07508247";
        using (var reader = new StringReader(texto)) { //só trocar para o arquivo aqui
            int size = int.Parse(reader.ReadLine());
            for (int i = 0; i < size; i++) {
                string[] linha = reader.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                WriteLine($"{linha[0]}, {linha[1]}, {linha[2]}"); //depois troca para o Vector3
            }
        }
    }
}

See running on .NET Fiddle . And no Coding Ground . Also I put it in GitHub for future reference .

    
21.07.2017 / 23:40
2

I understood your logic. You want to store information from values in text to vectors of three elements. Just do not understand if you want to do this to generate a single vector or want to store multiple vectors, but surely both cases are possible. You just need to define a logic for your text. If you are storing a fixed and unchanging number of three-number vectors, you can store everything in a 3x n array, where n is the number of column vectors to be stored (in this case, as specified as the first number in the text file). I call it "matrix" by its concept of linear algebra, but it is nothing more than an array of vectors, so it will be a Vector [ n ] type, as it is what you want.

Suppose you want to store everything in an array. In this implementation, what we would do is:

  • Read the first line to define the dimensions of an array (array of vectors);
  • Read each line of three numbers divided by spaces;
  • Split each string into its spaces;
  • Fill in the array with the strings obtained by converting them to float or double (depending on the precision you want). li>

    Here is the detailed implementation:

    using System;
    using System.Linq;
    
    namespace Programa
    {
          public class Program
          {
                Vector3[] Load(string filePath)  // Endereço do arquivo
                {
                    Vector3[] v;
                    using (StreamReader sr = new StreamReader(filePath))
                    {
                        string[] linha;
                        float[] nrs = new float[3];
                        int size = int.Parse(sr.ReadLine());  // Leio a primeira linha apenas, com o número de vetores da matriz
                        int i = 0;
                        v = new Vector3[size];
    
                        while (!sr.EndOfStream && i < size)
                        {
                            linha = sr.ReadLine().Split(' ');  // Divido pelos espaços
                                                               // Veja as outras sobrecargas de Split para mais opções
                            nrs = linha.Select(n => float.Parse(n)).ToArray();  // Uso Linq para selecionar cada elemento e converter para float
                            v[i] = new Vector3 (nrs[0], nrs[1], nrs[2]);
                            i++;
                        }
                    }
                    return v;
                }
          }
    }
    

    Instead of float.Parse, use double.Parse for double precision of decimal places if desired. Also, I always recommend (!!) using the using blocks as I used now, as they ensure that the StreamReader will be available after use.

    (Note: I have not tested the algorithm yet, I'm currently on Linux.) Of course, I'll edit later if there is a problem.)     

  • 22.07.2017 / 02:12