C#读取文件中的浮点数据

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
string path = "test.txt";
FileStream fs = new FileStream(path, FileMode.Open);
StreamReader sr = new StreamReader(fs);

char[] separator = new char[] { ' ', ',', '\t', '\r', '\n' };
string txt = sr.ReadToEnd().Trim().Replace("\r\n\r\n", "\r\n");
string[] lines = txt.Split(separator);

List<float> result = new List<float>(1024);
string[] nums;
float tmp;

for (int i = 0; i < lines.Length; i++)
{
nums = lines[i].Trim().Split(separator);
foreach(var num in nums)
{
if (num == "")
continue;
if(float.TryParse(num, out tmp))
{
result.Add(tmp);
}
else
{
Debug.Log("Format error at line " + (i + 1)+ ": " + num);
}
}
}

sr.Close();
fs.Close();