此代码引发异常,“索引超出了数组的范围”。这不应该简单地将每个拆分数据添加到指定的数组槽中吗?
while (input != null)
{
string[] splitInput = inputLine.Split();
EmpNum = int.Parse(splitInput[0]);
EmpName = (splitInput[1]);
EmpAdd = (splitInput[2]);
EmpWage = double.Parse(splitInput[3]);
EmpHours = double.Parse(splitInput[4]);
inputLine = (myFile.ReadLine());
Console.WriteLine("test {0},{1},{2}", EmpNum, EmpWage, EmpHours);
}
为了澄清一点,我正在从一个包含员工数据(姓名、地址、工作时间、员工编号、工资)的简单文本文件中读取数据。
为了清楚起见,我添加了整个主要方法。
using System;
using System.IO;
class Program
{
static void Main()
{
//declare an array of employees
Employee[] myEmployees = new Employee[10];
//declare other variables
string inputLine;
string EmpName;
int EmpNum;
double EmpWage;
double EmpHours;
string EmpAdd;
//declare filepath
string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\";
//get input
Console.Write("\nEnter a file name in My Documents: ");
string input = Console.ReadLine();
string path = environment + input;
Console.WriteLine("Opening the file...");
//read file
StreamReader myFile = new StreamReader(path);
inputLine = (myFile.ReadLine());
//split input
while (inputLine != null)
{
string[] splitInput = inputLine.Split();
EmpNum = int.Parse(splitInput[0]);
EmpName = (splitInput[1]);
EmpAdd = (splitInput[2]);
EmpWage = double.Parse(splitInput[3]);
EmpHours = double.Parse(splitInput[4]);
Console.WriteLine("test {0},{1},{2}", EmpNum, EmpWage, EmpHours);
}
Console.ReadLine();
}//End Main()
}//End class Program