如何将.txt文件中的数字读取为整数数组

本文关键字:读取 数字 整数 数组 txt 文件 | 更新日期: 2023-09-27 18:14:48

我有一个需要保存为数组的文件。我试图将文本文件转换为使用StreamReader的整数数组。我只是不确定在代码末尾的for循环中放入什么。

这是我目前为止写的:

//Global Variables
int[] Original;
//Load File
private void mnuLoad_Click_1(object sender, EventArgs e)
{
    //code to load the numbers from a file
    OpenFileDialog fd = new OpenFileDialog();
    //open the file dialog and check if a file was selected
    if (fd.ShowDialog() == DialogResult.OK)
    {
    //open file to read
    StreamReader sr = new StreamReader(fd.OpenFile());
    int Records = int.Parse(sr.ReadLine());
    //Assign Array Sizes
    Original = new int[Records];
    int[] OriginalArray;
    for (int i = 0; i < Records; i++)
    {
    //add code here
    }
}

.txt文件为:

    5
    6
    7
    9
    10
    2

PS我是一个初学者,所以我的编码技能是非常基本的!

更新:我以前有使用Line.Split的经验,然后将文件映射到数组,但显然这并不适用于这里,所以我现在该怎么办?

//as continued for above code
for (int i = 0; i < Records; i++)
{
    int Line = int.Parse(sr.ReadLine());
    OriginalArray = int.Parse(Line.Split(';')); //get error here
    Original[i] = OriginalArray[0];
}

如何将.txt文件中的数字读取为整数数组

您应该能够使用类似于上面的代码:

OriginalArray[i] = Convert.ToInt32(sr.ReadLine());

每次调用sr.ReadLine时,它将数据指针加1行,因此迭代文本文件中的数组

try this

OpenFileDialog fd = new OpenFileDialog();
if (fd.ShowDialog() == DialogResult.OK)
{
    StreamReader reader = new StreamReader(fd.OpenFile());
    var list = new List<int>();
    while (!reader.EndOfStream)
    {
        var line = reader.ReadLine();
        int value = 0;
        if (!string.IsNullOrWhiteSpace(line) && int.TryParse(line, out value))
            list.Add(value);
    }
    MessageBox.Show(list.Aggregate("", (x, y) => (string.IsNullOrWhiteSpace(x) ? "" : x + ", ") + y.ToString()));
}

可以将整个文件读入字符串数组,然后进行解析(检查每个字符串的完整性)。

类似:

int[] Original;
//Load File
private void mnuLoad_Click_1(object sender, EventArgs e)
{
    //code to load the numbers from a file
    var fd = new OpenFileDialog();
    //open the file dialog and check if a file was selected
    if (fd.ShowDialog() == DialogResult.OK)
    {
        var file = fd.FileName;
        try
        {
            var ints = new List<int>();
            var data = File.ReadAllLines(file);
            foreach (var datum in data)
            {
                int value;
                if (Int32.TryParse(datum, out value))
                {
                    ints.Add(value);
                }
            }
            Original = ints.ToArray();
        }
        catch (IOException)
        {
            // blah, error
        }
    }
}

另一种方法是如果你想读到文件的末尾,而你不知道它有多长,使用while循环:

String line = String.Empty;
int i=0;
while((line = sr.ReadLine()) != null)
{
    yourArray[i] = Convert.ToInt32(line);
    i++;
    //but if you only want to write to the file w/o any other operation
    //you could just write w/o conversion or storing into an array
    sw.WriteLine(line); 
    //or sw.Write(line + " "); if you'd like to have it in one row
}
//using linq & anonymous methods (via lambda)
string[] records = File.ReadAllLines(file);
int[] unsorted = Array.ConvertAll<string, int>(records, new Converter<string, int>(i => int.Parse(i)));