Alireza
Alireza

Reputation: 21

I want to read some double data from text file in C#

my double data in text file like below:

1.4  2.3  3.4
2.2  2.5  2.5

I want simply read this data from file and store it in an array.

please help me. I'm a beginner in C#

Upvotes: 1

Views: 3697

Answers (4)

Lasse Espeholt
Lasse Espeholt

Reputation: 17782

Try this, it should be somewhat more bulletproof than some of the other answers. It does not check for invalid data entries which can't be parsed correctly.

var doubles = File.ReadAllText(path)
              .Split(new[] {" ", "\r\n", "\n"}, StringSplitOptions.RemoveEmptyEntries)
              .Select(s => double.Parse(s, CultureInfo.GetCultureInfo("en-US"))).ToArray();

This will work if the doubles are splitted by either a space or a line break. And it also works if there are multiple spaces/line breaks. I live in DK so I have setted the culture info explicit for parsing.

Upvotes: 0

Gishu
Gishu

Reputation: 136613

Consult MSDN with the following pointers...

File class to read the file contents as string
String.Split to split the numbers based on your delimited
and Double.Parse to convert from string into double.

Upvotes: 1

Botz3000
Botz3000

Reputation: 39610

var values = from value in File.ReadAllText("C:\\Yourfilename.txt").Split(' ')
             select double.Parse(value);

Upvotes: 0

SLaks
SLaks

Reputation: 887453

You can use LINQ:

double[] numbers = 
    File.ReadAllLines(path)
        .Select(s => double.Parse(s)
        .ToArray()

If each line can have multiple numbers, you'll need to split the lines:

double[] numbers = 
    File.ReadAllLines(path)
        .SelectMany(s => s.Split(' '))
        .Select(s => double.Parse(s)
        .ToArray()

You can also use a normal loop:

List<double> numbers = new List<double>();
foreach(string line in File.ReadAllLines(path)) {
    numbers.Add(Double.Parse(line));
}

Or, to split them,

List<double> numbers = new List<double>();
foreach(string line in File.ReadAllLines(path)) {
    foreach(string word in line.Split(' ') {
        numbers.Add(Double.Parse(word));
    }
}

Upvotes: 4

Related Questions