简体   繁体   English

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

[英]How to read numbers in a .txt file to an integer array?

I have a file that I need to save as an array. 我有一个文件需要保存为数组。 I am trying to convert a text file to an integer array using StreamReader . 我正在尝试使用StreamReader将文本文件转换为整数数组。 I just am unsure as to what to put in the for loop at the end of the code. 我只是不确定在代码末尾放在for循环中的内容。

This is what I have so far: 这是我到目前为止的内容:

//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
    }
}

The .txt file is: .txt文件是:

    5
    6
    7
    9
    10
    2

PS I am a beginner, so my coding skills are very basic! PS我是一个初学者,所以我的编码技能非常基础!

UPDATE: I have previous experience using Line.Split and then mapping file to arrays but obviously that does not apply here, so what do I do now? 更新:我以前有使用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];
}

You should just be able to use similar code to what you had above it: 您应该能够使用与其上方相似的代码:

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

Every time the sr.ReadLine is called it increments the data pointer by 1 line, hence iterating through the array in the text file. 每次调用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()));
}

You can read the entire file into a string array, then parse (checking the integrity of each one). 您可以将整个文件读入一个字符串数组,然后进行解析(检查每个文件的完整性)。

Something like: 就像是:

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

Another way to do it if you'd like to read to the end of the file and you don't know how long it is with a while loop: 如果您想读到文件末尾并且不知道使用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)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM