c# - 在 C# 中使用文件 I/O
问题描述
我有一个 C# 项目,用于我的面向对象编程课程,我必须根据我提供的 .txt 处理考试及其问题,然后吐出一些关于考试的信息。https://gyazo.com/2f67407adf82fe4d071382bfdee5219e这是txt文件,第一行是每个问题的答案,接下来的每一行都是学生号和他们的回答,0表示.txt文件的结尾(x代表没有给出的答案)。该程序需要计算学生的最终分数,旁边有学生编号、学生数量、每个问题的正确回答数、最低/最高分数和所有学生的平均分数。正确答案是+4,错误答案是-1,没有答案是0。程序需要像这样将此信息输出到控制台。https://gyazo.com/0f1d80eeb6f44681bf6ab80f5934dcf8(减去最高、最低和平均分数)并将其打印到 .txt 文件中。这是我目前拥有的代码,但对如何继续该程序感到困惑。
String line;
string[] tokens;
int id;
try
{
//Pass the file path and file name to the StreamReader constructor
StreamReader sr = new StreamReader("c:\\exam.txt");
//Read the first line of text
line = sr.ReadLine();
Console.WriteLine(line);
line = sr.ReadLine();
tokens = line.Split();
id = Convert.ToInt32(tokens[0]);
//Continue to read until you reach end of file
while (id != 0)
{
//write the line to console window
Console.WriteLine(tokens[1]);
//Read the next line
line = sr.ReadLine();
tokens = line.Split();
id = Convert.ToInt32(tokens[0]);
}
//close the file
sr.Close();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
解决方案
您需要将每个正确答案与每个学生的答案进行比较。这应该让你开始:
//Read the first line of text
string line = sr.ReadLine();
// Correct answers
string [] answerKey = line.Split();
while (true)
{
line = sr.ReadLine();
tokens = line.Split();
id = Convert.ToInt32(tokens[0]);
if (id == 0) break;
string [] studentAnswers = tokens[1].Split();
int score = 0;
// Compare correct answers to student answers
for (int i = 0; i < answerKey.Length; i++) {
if (answerKey[i] == studentAnswers[i]) {
score += 4;
}
else if (studentAnswers[i] != "X") {
score -= 1;
}
}
// Do something with score here.....
}
//close the file
sr.Close();
Console.ReadLine();
推荐阅读
- javascript - 在 Vue 3 中使用 Vuex 4 模块和 TypeScript,以及如何修复循环依赖 linting 错误?
- c++ - 是否可以在类定义中使用类对象作为变量?
- dart - 使用 dartz 中的 Either 时出现编译器错误
- reactjs - 如何使用 useRef 获取多个单击元素的文本?
- alibaba-cloud - 如何限制对 OSS 上文件的访问,同时仍然允许使用 wget 或 curl 下载
- java - Java 将 Selenium Grid 作为标准 Java 软件运行
- if-statement - SwiftUI - 为什么我不能在 if 语句中使用警报
- sql - PostgreSQL 是否有办法以本地名称而不是英文返回月份名称?
- assembly - 在 x86 处理器上运行 ARM 程序集?
- react-native - 父 ScrollView 停止滚动时子 ScrollView 不滚动