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

标签 c# arrays string double text-files

这些是文本文件中的

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/

相关文章:

c - 使用转义键进行字符串操作

c# - 为什么我不能通过索引访问 KeyedCollection 项目?

java - 将字符串的字节复制到所选字符集中的所选数组

ios - 在 swift 中创建图像数组并连接声音

python - 如果列表包含字符串,则打印列表中包含它的所有索引/元素

C 程序计算输入单词列表中有多少个元音字母

c# - 如何在 Azure 中以辅助角色运行 RavenDb

c# - 从时区转换后将日期格式更改为 dd/MM/yyyy

c# - ASP.Net C# - 动态删除控件

java - 我无法向用户显示输出