【问题标题】:How to read numbers in a .txt file to an integer array?如何将 .txt 文件中的数字读入整数数组?
【发布时间】:2015-09-27 17:06:37
【问题描述】:

我有一个需要保存为数组的文件。我正在尝试使用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];
}

【问题讨论】:

    标签: c# arrays streamreader


    【解决方案1】:

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

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

    每次调用 sr.ReadLine 时,它都会将数据指针增加 1 行,从而遍历文本文件中的数组。

    【讨论】:

    • OMG 刚刚看到你的答案!非常感谢!你的回答超级简单,让我意识到我想太多了哈哈!
    【解决方案2】:

    试试这个

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

    【讨论】:

      【解决方案3】:

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

      类似:

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

      【讨论】:

        【解决方案4】:

        如果您想读到文件末尾并且不知道使用 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
        }
        

        【讨论】:

          【解决方案5】:
          //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)));
          

          【讨论】:

            猜你喜欢
            • 2015-11-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-01-28
            相关资源
            最近更新 更多