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

How can I read and store specific part of a line from a file using c++?

本文关键字:存储 定部 读取 c++ 何使用 文件      更新时间:2023-10-16

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

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

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

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

#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++;
  }


}

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

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 << "Yesn";
        file << "Non"; 
        file << "Mabyen"; 
    }
    // 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'; 
        }
    }
}