System.FormatException 已抛出输入字符串格式不正确

System.FormatException has been thrown input string was not in a correct format

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FajlbolOlvasas
{
    class Program
    {
        struct Student
        {
            public string name;
            public double avarage;
        }
        static void Main(string[] args)
        {
            StreamReader f = new StreamReader("joci.txt");
            Student[] students = new Student[Convert.ToInt32(f.ReadLine())];
            for (int i = 0; i < tanulok.Length && !f.EndOfStream; i++)
            {
                students[i].name = f.ReadLine();
                students[i].avarage = Convert.ToDouble(f.ReadLine());
                Console.WriteLine(students[i].name + " - " + students[i].avarage);
            }
            f.Close();
            Console.ReadKey();
        }
    }
}

txt 文件保存在 bin/Release 控制台出现,但那只是一个空的 它说 System.FormatException 已被抛出 输入字符串格式不正确

txt文件的内容是:
托米
4

3
鲍勃
5

好吧,除了 FormatException 这个主要问题外,我几乎没有看到其他问题。

第一个是您正在将 "unknown" 文件内容处理成数组而不是列表。如果您使用以下示例了解文件的结构,则可以跳过此步骤:

string[] fileContents = File.ReadAllLines("joci.txt");
Student[] students = new Student[fileContents.Lengthe / 2]; // because 2 lines describes student

但更好的解决方案是使用 List<> 而不是数组:

List<Student> students = new List<Student>();

接下来 完全 错误的是您假设您知道文件内容。你应该总是为错误留一些余地,首先尝试转换类型而不是要求类型转换:

string line = f.ReadLine();
int convertedLine = 0;
if ( int.TryParse( line, out convertedLine ) ) {
    // now convertedLine is succesfully converted into integer type.
}

所以做出最后的结论:

总是为错误留出一些空间。

很好(但仍然不是最好的)解决您问题的方法是:

string[] fileContents = File.ReadAllLines("joci.txt");
Student[] students = new Student[fileContents.Length / 2];
for (int i = 0, j = 0; i < fileContents.Length; i += 2, j++)
{
    string name = fileContents[i];
    int av = 0;
    if ( int.TryParse( fileContents[i + 1], out av ) {
        students[j] = new Student { name = name, average = av };
        Console.WriteLine(students[j].name + " - " + students[j].avarage);
    }
}
Console.ReadKey();