从文件中读取双精度浮点数并将它们存储在数组中,然后在列表框中显示。

3

这些是来自文本文件

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

数字是每行一个吗? - Matthew Watson
是的,要在列表框中显示。 - user2451489
2个回答

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

如果你在谈论 UTF8,难道不应该明确指定它,像这样 File.ReadLines(filename, Encoding.UTF8) 吗? - Ilya Ivanov
我目前非常困惑,文件类型是 .txt。 - user2451489
根据File.ReadLines()的文档:“此方法使用UTF8作为编码值。” - Matthew Watson
@MatthewWatson 嗯,实际上文档说明如下:该方法尝试根据字节顺序标记的存在自动检测文件的编码。可以检测到UTF-8和UTF-32(大端和小端)编码格式。 来源 - Ilya Ivanov
@IlyaIvanov 是的,好观点 - 解析为双精度将确保只能使用有效的双精度(否则会引发异常)。如果 ListBox 项在某个地方被转换为双精度,则这也很重要。 - Matthew Watson
显示剩余3条评论

0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接