使用带有流编写器的for循环

时间:2017-02-07 14:51:05

标签: c# arrays visual-studio for-loop streamwriter

我正在尝试创建一个包含多个属性的问题对象,所有这些属性都存储在文本文件中并使用StreamReader进行检索。

一个属性是数组Choices[]。我需要所述数组能够根据qType变量的值进行填充。

例如:if qType = "button",然后Choices[]应该只读取文件中的4行。而if qType = "dragdrop"Choices[]应从文件中读取6次。到目前为止,我尝试使用for循环,case语句和if语句 - 所有这些都已中断。有人能告诉我如何在不中断StreamReader的情况下做到这一点吗?

这是有效的代码:

using (var quizFileReader = new System.IO.StreamReader("PhysQuestions.txt"))
{
    string line;
    Question question;

    // Loop through the lines of the file until there are no more (the ReadLine function return null at this point).
    // ReadLine called here only reads question texts (first line of a question), while other calls to ReadLine read the choices.
    while ((line = quizFileReader.ReadLine()) != null)
    {
        // Skip this loop if the line is empty.
        if (line.Length == 0)
            continue;

        // Create a new question object.
        // The "object initializer" construct is used here by including { } after the constructor to set variables.
        question = new Question()
        {
            // Set the question text to the line just read.
            QuestionText = line,
            qType = quizFileReader.ReadLine(),
            // Set the choices to an array containing the next 4 lines read from the file.
            Choices = new string[]
            { 
                quizFileReader.ReadLine(), 
                quizFileReader.ReadLine(),
                quizFileReader.ReadLine(),
                quizFileReader.ReadLine(),
            },

            hintTxt = quizFileReader.ReadLine(),
            difficulty = Convert.ToDouble(quizFileReader.ReadLine()),
            imgPath = quizFileReader.ReadLine()
        };
    }
}

我试图做的事情不起作用:

Choices = new string[]
{ 
    for(int i=0; i<4; i++)
    {
        quizFileReader.ReadLine(), // expects a ;
    }
}, // excepts a ;

继承我正在使用的完整代码:

    public string QuestionText, imgPath, hintTxt; // Actual question text.
    public string[] Choices;    // Array of answers from which user can choose.
    public int Answer, qNum, linesToRead;          // Index of correct answer within Choices.
    public double difficulty;  // Double that represents difficulty of each question

    public List<Question> getQues() // reads questions from text file, assigns all strings in text file to index of List, returns the full list of questions
    {
        // Create new list to store all questions.
        var questions = new List<Question>();

        // Open file containing quiz questions using StreamReader, which allows you to read text from files easily.
        using (var quizFileReader = new System.IO.StreamReader("PhysQuestions.txt"))
        {
            string line;
            Question question;

            // Loop through the lines of the file until there are no more (the ReadLine function return null at this point).
            // ReadLine called here only reads question texts (first line of a question), while other calls to ReadLine read the choices.
            while ((line = quizFileReader.ReadLine()) != null)
            {
                // Skip this loop if the line is empty.
                if (line.Length == 0)
                    continue;

                // Create a new question object.
                // The "object initializer" construct is used here by including { } after the constructor to set variables.
                question = new Question()
                {
                    // Set the question text to the line just read.
                    QuestionText = line,
                    linesToRead = Convert.ToInt32(quizFileReader.ReadLine()),
                    Choices = new string[linesToRead];
                     for (int i=0; i < linesToRead; i++)
                    {
                      Choices[i] = await quizFileReader.ReadLineAsync();
                    }


                     hintTxt = await quizFileReader.ReadLineAsync();
                    difficulty =  Convert.ToDouble(quizFileReader.ReadLine());
                    imgPath = quizFileReader.ReadLine();

                };

                // Set correct answer to -1, this indicates that no correct answer has been found yet.
                question.Answer = -1;

                // Check each choice to see if it begins with the '!' char (marked as correct).
                for (int i = 0; i < 4; i++)
                {
                    if (question.Choices[i].StartsWith("!"))
                    {
                        // Current choice is marked as correct. Therefore remove the '!' from the start of the text and store the index of this choice as the correct answer.
                        question.Choices[i] = question.Choices[i].Substring(1);
                        question.Answer = i;
                        break; // Stop looking through the choices.
                    }
                }

                // Check if none of the choices was marked as correct. If this is the case, we throw an exception and then stop processing.
                if (question.Answer == -1)
                {
                    throw new InvalidOperationException(
                        "No correct answer was specified for the following question.\r\n\r\n" + question.QuestionText);
                }






                // Finally, add the question to the complete list of questions.
                questions.Add(question);
            }

            return questions;
        }
    }

1 个答案:

答案 0 :(得分:0)

一旦你知道你想读多少行就做类似的事情:

using (var quizFileReader = new System.IO.StreamReader("PhysQuestions.txt"))
{
    Question question;
    int linesToRead = 4;
    string[] choices = new string[linesToRead];

    for (int i=0; i < linesToRead; i++)
    {
        choices[i] = await quizFileReader.ReadLineAsync();
    }
}

这应该让你开始朝着正确的方向前进,但是如果你被困在某个地方,请告诉我。

我还将ReadLine转换为异步版本,因此它不会阻止。