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/preame控制台出现,但这只是一个空的它说system.formatexception已被抛出的输入字符串不是正确的格式
TXT文件的内容是:
tomi
4
李
3
鲍勃
5
好吧,除了主要问题(是构建问题),我很少看到其他问题。
第一个是您将"未知"文件内容处理到数组而不是列表中。如果您知道文件是如何使用以下示例构造的,则可以跳过:
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();