首页 > 解决方案 > 在 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.");
        }

标签: c#

解决方案


您需要将每个正确答案与每个学生的答案进行比较。这应该让你开始:

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

推荐阅读