繁体   English   中英

文件流到对象向量

[英]File stream into Object vector

class Question
{
public:

    void showQuestion();
    bool checkAnswer(string givenAnswer);
    void showAnswer();
    void markCorrect();

private:

    string level;
    string questionText;
    string answerText;
    bool correct;
};

class Quiz
{
public:

    bool loadQuestions(string dataFileName);
    void dumpQuestions();
    int deliverQuiz();

private:

    vector<Question> questions;

};

我这里有两个类,Question和Quiz,我需要阅读一个文本文件,其中包含问题,答案等。 读取文件后,我需要将变量存储到向量中。 我尝试了几件事,创建了一个Question对象向量并将其存储在其中。 但是,我相信我需要创建一个Quiz对象并将其存储在私有向量中。 我很困惑如何将变量存储到Quiz向量对象中,或者语法如何。

换句话说,创建一个问题对象向量并将其存储在其中对我来说很有意义。 但是,看来我需要创建一个测验对象向量,并在其中存储变量,我只是不确定如何去做。

这是我的名为questions.txt的输入文件格式的示例

S|1|What is the capital of Italy|Rome
S|1|What is the capital of France|Paris

但是,看来我需要创建一个测验对象向量,并将变量存储在其中

我认为您不需要这样做。 在您的示例中,您有1个测验,其中包含许多问题。 这是有道理的,因此我认为您无需创建Quiz对象向量。

我需要阅读一个文本文件,其中将包含问题,答案等。阅读文件后,我需要将变量存储到向量中。

这是通过实现已定义的Quiz::loadQuestions()方法来填充Question对象向量的方法。 您将需要提供对Question对象的私有成员的访问权限,以便正确地检索和填充它们(提供访问器和更改器)。

void Question::setLevel( const int theLevel )
{
   level = theLevel;
}

void Question::setQuestion( const std::string & question )
{
   questionText = question;
}

等等。 完成此操作并指定输入文件格式后,您可以像这样填充。

bool Quiz::loadQuestions( const std::string & fileName )
{
    std::ifstream infile(fileName.c_str());
    if (infile.is_open())
    {
        std::string line;
        while (std::getline(infile, line))
        {
            std::stringstream ss(line);
            std::string token;
            Question temp;

            std::getline(ss, token, '|'); // Type (don't care?)
            std::getline(ss, token, '|'); // Level
            int level = atoi(token.c_str());
            temp.setLevel(level);

            std::getline(ss, token, '|'); // Question
            temp.setQuestion(token);

            std::getline(ss, token, '|'); // Answer
            temp.setAnswer(token);

            // store populated Question object for Quiz
            questions.push_back(temp);
        }
    }
    return (!questions.empty());
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM