我的文件包含这些数字
123.4 23.7 89.2 ......
45.8
...
8列和1024行,我希望逐行读取此文件,并将每行放在double数组中以获取此行中的最小数字,并将此最小数字放在大小为1024的数组中。
我在c#...
中尝试了这段代码 static void Main(string[] args)
{
string line;
double[] row = new double[8];
double[] minimum = new double[1024];
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader("c:\\test.txt");
for (int k = 0; k < 1024; k++)
{
while ((line = file.ReadLine()) != null )
{
string[] numbers = new string[8];
int numCount = 0;
for (int i = 0; i < line.Length; i++)
{
if (line[i] != ' ')
{
numbers[numCount] = "";
while (line[i] != ' ')
{
numbers[numCount] += line[i];
i++;
}
numCount++;
}
}
for (int i = 0; i < 8; i++)
{
row[i] = Convert.ToDouble(numbers[i]);
}
double min = row[0];
for (int j = 0; j < 8; j++)
{
if (row[j] <= min)
min = row[j];
}
minimum[k] = min;
}
}
Console.WriteLine("The array contain:");
for (int i = 0; i < 1024; i++)
Console.WriteLine(minimum[i]);
file.Close();
// Suspend the screen.
Console.ReadLine();
}
答案 0 :(得分:4)
有几种方法可以简化您的代码 - File.ReadLines,String.Split和LINQ Select。结果代码可能类似于:
var listOfArraysOfDouble = File.ReadLines(fileName)
.Select(row =>
row.Split((string[]) null, StringSplitOptions.RemoveEmptyEntries)
.Select(columnValue => double.Parse(columnValue))
.ToArray()
);