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

时间:2016-12-09 13:37:58

标签: c# streamreader

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

1 个答案:

答案 0 :(得分:1)

好的,除了主要问题是FormatException之外,我看到其他几个。

首先,您要将“未知”文件内容处理为数组而不是列表。如果您通过以下示例了解文件的结构,则可以跳过此步骤:

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