这些是文本文件
中的值
1245.67
1189.55
1098.72
1456.88
2109.34
1987.55
1872.36
它们显然是十进制
不确定我遗漏了什么但是当我调试时我得到输入字符串格式不正确 任何帮助都会很棒
这就是我到目前为止编写的代码
private void getValuesButton_Click(object sender, EventArgs e)
{
try
{
//create an array to hold items read from the file.
const int SIZE = 7;
double[] numbers = (double[])ois.readObject();
// Counter variable to use in the loop
int index = 0;
//Declare a StreamReader variable
System.IO.StreamReader inputFile;
//Open the file and get a StreamReader object.
inputFile = File.OpenText("Values.txt");
//Read the file contents into the array.
while (index < numbers.Length && !inputFile.EndOfStream)
{
numbers[index] = int.Parse(inputFile.ReadLine());
index++;
}
//Close the file.
inputFile.Close();
//Display the array elements in the list box.
foreach (double value in numbers)
{
outputListbox.Items.Add(value);
}
}
catch (Exception ex)
{
//Display an error message.
MessageBox.Show(ex.Message);
}
最佳答案
如果文件是 UTF8 格式并且每行只包含一个 float ,您可以将它们全部解析成这样的序列(在当前语言环境中)
var fileNumbers = File.ReadLines(filename).Select(double.Parse);
这是有效的,因为 File.ReadLines()
返回 IEnumerable<string>
它按顺序返回文件中的每个字符串。然后我使用 Linq 的 Select()
申请double.Parse()
到每一行,这有效地将字符串序列转换为 double 序列。
然后你可以像这样使用序列:
int index = 0;
foreach (var number in fileNumbers)
numbers[index++] = number;
或者可以省略中介numbers
数组并将它们直接放入列表框中:
foreach (var number in fileNumbers)
outputListbox.Items.Add(number);
你可以用两行来完成整个事情,但这样的可读性要差得多:
foreach (var number in File.ReadLines("filename").Select(double.Parse))
outputListbox.Items.Add(number);
最后,正如下面 Ilya Ivanov 所指出的,如果您只需要列表框中的字符串,您可以简单地这样做:
outputListbox.Items.AddRange(File.ReadAllLines(filename));
关于c# - 从文件中读取 double 值并将它们存储在数组中然后显示在列表框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16916662/