如何使用c ++从文件读取和存储行的特定部分?

时间:2019-06-14 17:56:09

标签: c++ file-handling

我正在尝试使用c ++制作测验游戏,因为我想将我所有的问题(MCQ)及其答案逐行存储在文本文件中。

采用以下格式 “这是什么?a)x b)y c)z d)p”'a'

现在我想从文件中读取文件并将其存储在测验游戏中。这是一个字符串变量中的问题,而一个char变量中的答案。

然后我要检查用户输入的答案是否正确。

#include <iostream>
#include <fstream>

 using namespace std;


 int NoOfQuestions = 2;
int counter = 0;
 int main(){
  ifstream file("c++.txt");

  string question;
  char a;

  while(counter<NoOfQuestions){

      getline(file,question);
      cout<<question<<endl;
      counter++;
  }




}

1 个答案:

答案 0 :(得分:2)

假设您的文件如下所示。你有两个问题。第一个有3个答案,第二个有2个答案:

Is the Earth flat?
3
Yes
No
Maybe
Is the sky blue?
2
Yes
It's cloudy

我们可以创建一个表示问题的结构:

struct Question {
    std::string question;
    std::vector<std::string> answers; 
};

然后我们可以编写一个函数来使用>>运算符读取它:

std::istream& operator>>(std::istream& stream, Question& q) {
    // Get the question
    std::getline(stream, q.question);

    // Get the number of answers
    int num_answers;
    stream >> num_answers; 

    // Ignore the rest of the line containing the number of answers
    std::string _ignore; 
    std::getline(stream, _ignore); 

    // Read the answers
    q.answers.resize(num_answers); 
    for(auto& answer : q.answers) {
        std::getline(stream, answer); 
    }
    return stream; 
}

用法示例:

int main() {
    // First block: write the file and close it
    {
        std::ofstream file("test.txt");
        file << "Is the earth flat?\n";
        file << "3  \n"; 
        file << "Yes\n";
        file << "No\n"; 
        file << "Mabye\n"; 
    }

    // Second block: open the file, and read it
    {
        std::ifstream file("test.txt");
        Question q;
        file >> q;
        std::cout << "Question: " << q.question << '\n'; 
        std::cout << "Answers: \n"; 

        for(auto& answer : q.answers) {
            std::cout << answer << '\n'; 
        }

    }
}