【发布时间】:2026-01-22 07:55:02
【问题描述】:
我创建了一个项目,该项目从 CSV 文件中读取,该文件包含班级中学生的姓名和分数。该程序应该从 CSV 文件中读取,然后输出所有名称。我已经创建了这个程序并且它可以工作,只是我只能输出班级中 1 名学生的姓名和分数,而这意味着 12 名学生。如果有人能告诉我我需要在哪里更改我的代码以便获得整个班级的输出,将不胜感激。谢谢。
public static void Main(string[] args)
{
string[] names = loadNames();
int[] marks = loadMarks();
outputMarks(names, marks);
Console.ReadKey();
}
static string[] loadNames()
{
string filename = @"testMarks.csv";
string[] tempData;
string[] tempNames = new string[2];
using (StreamReader currentfile = new StreamReader(filename))
{
tempData = currentfile.ReadLine().Split(',');
}
tempNames[0] = tempData[0];
tempNames[1] = tempData[1];
return tempNames;
}
static int[] loadMarks()
{
string filename = @"testMarks.csv";
string[] tempData;
using (StreamReader currentfile = new StreamReader(filename))
{
tempData = currentfile.ReadLine().Split(',');
}
int[] tempMarks = new int[tempData.Length - 2];
for (int i = 2; i < tempData.Length; i++)
{
tempMarks[i - 2] = int.Parse(tempData[i]);
}
return tempMarks;
}
static void outputMarks(string[] names, int[] marks)
{
for (int i = 0; i < 2; i++)
{
Console.Write(names[i] + "\t");
}
for (int i = 0; i < 6; i++)
{
Console.Write(marks[i] + "\t");
}
Console.WriteLine();
}
}
}
【问题讨论】:
-
你不能。电子表格是一种二维数据结构,您只使用一维数组。
-
看看使用 Github 的 CSVHelper 可能真的有帮助。
-
@IanKemp 那么我需要在我的代码中添加二维数组吗?