juliana
juliana

Reputation: 23

error read from file c#

I want to read double numbers from a text file and store it in array of array type double. I tried this code

int h = 0;
int g = 0;
string lini = File.ReadAllText(@"C:2.txt");
double[][] datafile1 = new double[30][];
foreach (var row in lini.Split('\n'))
{
    h = 0;
    datafile1[g] = new double[7];
    foreach (var col in row.Trim().Split(','))
    {
        datafile1[g][h] = double.Parse(col);
        h++;
    }
    g++;
}

but it's only works with this file numbers type why?

5.1, 3.5, 1.4, 0.2, 0, 0, 1
4.9, 3.0, 1.4, 0.2, 0, 0, 1
4.7, 3.2, 1.3, 0.2, 0, 0, 1

when I try to change the file it gives me error Input string was not in a correct format for this file Why?

0.000000 1.000000 0.000000 0.000000 0.000000 0.500000 0.500000 0.500000
0.000000 0.000000 0.000000 0.333333 1.000000 0.500000 0.500000 0.000000

Upvotes: 0

Views: 305

Answers (2)

Christos
Christos

Reputation: 53958

but it's only works with this file numbers type why?

It works only with this file because this file has 7 numbers per row and each on of them is separated from its next or previous number with a comma.

The other format you have mentioned is apparently different from this. This is why you get an error.

Provided that the other file you have mentioned has a structure per row like the one you have presented, you should change your code like below:

foreach (var row in linijos.Split('\n'))
{
    h = 0;

    // passing a list of separators, you catch both of your cases.
    columns = row.Trim().Split(new[] { ',', ' '}));

    // You read dynamically the number of columns, instead of having to set 
    // the correct number
    datafile1[g] = new double[columns.Length];

    foreach (var column in columns)
    {
        datafile1[g][h] = double.Parse(column);
        h++;
    }
    g++;
}

UPDATE

int h = 0;
int g = 0;
var rows = File.ReadAllLines(@"C:2.txt");
double[][] datafile1 = new double[lines.Length][];
foreach (var row in rows)
{
    h = 0;

    // passing a list of separators, you catch both of your cases.
    columns = row.Trim().Split(new[] { ',', ' '}));

    // You read dynamically the number of columns, instead of having to set 
    // the correct number
    datafile1[g] = new double[columns.Length];

    foreach (var column in columns)
    {
        datafile1[g][h] = double.Parse(column);
        h++;
    }
    g++;
}

Upvotes: 1

Maksim Simkin
Maksim Simkin

Reputation: 9679

IN your second example you don't have any commas between numbers, so either edit your input file, or add space to possible delimiters:

    foreach (var col in row.Trim().Split(new[] { ',', ' '}))
    {
        datafile1[g][h] = double.Parse(col);
        h++;
    }

Upvotes: 2

Related Questions