从文件中读取双值并将它们存储在数组中然后显示在列表框中

时间:2013-06-04 11:29:45

标签: c# arrays string double text-files

这些是values

中的textfile
1245.67
1189.55
1098.72
1456.88
2109.34
1987.55
1872.36

他们显然是decimal s

不确定我错过了什么但是当我调试时我得到的输入字符串格式不正确 任何帮助都会很棒

那是我到目前为止编码的那些

    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);
        }

2 个答案:

答案 0 :(得分:1)

如果文件是UTF8格式并且每行只包含一个浮点数,则可以将它们全部解析为类似的序列(在当前语言环境中)

var fileNumbers = File.ReadLines(filename).Select(double.Parse);

这是有效的,因为File.ReadLines()返回IEnumerable<string>,它按顺序返回文件中的每个字符串。然后我使用Linq的Select()double.Parse()应用于每一行,这有效地将字符串序列转换为一系列双精度。

然后你可以使用这样的序列:

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));

答案 1 :(得分:0)

看起来你做了int.parse,你试图解析一个double,而不是一个int,所以使用Double.Parse读取数组,这应该可以正常工作。