【问题标题】:How can I read and store specific part of a line from a file using c++? [closed]如何使用 c++ 从文件中读取和存储行的特定部分? [关闭]
【发布时间】:2019-06-14 17:56:09
【问题描述】:

我正在尝试使用 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++;
  }




}

【问题讨论】:

标签: c++ file-handling


【解决方案1】:

假设您的文件如下所示。你有两个问题。第一个有 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; 
};

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

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'; 
        }

    }
}

【讨论】:

    猜你喜欢
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    相关资源
    最近更新 更多