这是读取文件输入的正确方法吗?

时间:2019-02-04 07:43:47

标签: c++ c++11

这是从文件中读取一行,将其拆分为2个变量(一个文本和一个答案),然后将这两个变量输入到我创建的类的向量中的正确方法吗?

例如,如果我有一个包含问题和答案列表的文本文件,这将是我如何阅读同一行中的每个问题和答案的方式 “ 12英尺有几英寸?”

Question_Bank::Question_Bank(){};

Question_Bank::Question_Bank(std::string fileName){
    std::cout<<"Please enter the name of the file containing your questions: ";
    cin>>fileName;
    questionsFile.open(fileName);
    while (questionsFile.fail())
            {
            cout<<"Unable to open the file."<<endl;
            std::cout<<"Please enter the name of the file containing your questions: ";
            cin>>fileName;
            questionsFile.open(fileName);
            }
}

void LoadQuestions(){
    std::string blank;
    std::string text;
    std::string answer;
    std::string line;

    while (std::getline (questionsFile, line ) {
    std::stringstream ss(line);
    ss>>answer>>blank;
    getline(ss, text);
    questions.Question(text, answer).push_back();
    if (questionsFile.eof()){
            break;
            }
    }
questionsFile.close();
}

Question GetNextQuestion(){
    return questions;
}

问题类

Question::Question(){};

Question::Question(std::string text, std::string answer){
    this->text = text;
    this->answer = answer;
}

std::string Question::GetText(){
    return text;
}

bool Question::AnswerContainsDigit(char digit){
    if (isdigit digit){
    return true
    }
    else return false;
}

std::string Question::GetAnswerWithPlaceholder(std::vector<char> answH){
string tempAnswer = "___"; //3 underscores
    for (int x=0; x < answH.size(); x++){
            for (int y = 0; y < tempAnswer.size(); y++){
                    if (answer.at(y)== answH.at(x){
                            tempAnswer.at(y) = answH.at(x)
                    }
            }
    }
return tempAnswer;
}

bool Question::AllDigitsGuessed(std::string userGuess){
    if (userGuess == answer)
    return true;
    else return false;
}

问题和答案的示例如下:

206 How many bones are in the average adult human?
2000 How many yards are in a nautical mile?

1 个答案:

答案 0 :(得分:0)

我猜不是

questions.Question(text, answer).push_back();

您可以使用

questions.push_back(Question(text, answer));