从输入文件中读取直到字符串出现在 C++ 中

Read from a input file until a string appears in C++

我有一个如下所示的输入文件 -

BEGIN
ABC
DEF
END
BEGIN
XYZ
RST
END

我必须提取从 BEGIN 到 END 的所有内容并将它们存储在一个字符串中。所以,从这个文件我将有两个字符串。我正在使用 ifstream 来读取输入文件。我的问题是,如何解析输入文件以获取从一个 BEGIN 到下一个 END 的所有内容。 getline() 有字符作为分隔符,而不是字符串。我尝试的另一种方法是将输入文件中的所有内容复制到字符串,然后根据 .find() 解析字符串。但是,在这种方法中,我只得到第一个 BEGIN 到 END。

有什么方法可以将输入文件中的所有内容存储在一个字符串中,直到某个字符串出现 (END)?

出于存储目的,我使用vector<string> 来存储。

bool start = false;
vector<string> v;

while (...)
{
  string line = ifs.getline();
  if (line == "START")
  {
    start = true;
    continue;
  }
  if (line == "END")
  {
    start = false;
    process(v);
    v.clear();
    continue;
  }
  if (start)
    v.push_back(line);
}

用正确的名称替换文件名。

#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
#include <string>

using namespace std;

int main()
{
    char filename[] = "a.txt";
    std::vector<string> v;
    std::ifstream input(filename);
    string temp = "";
    for(std::string line; getline( input, line ); )
    {
        if(string(line) == "BEGIN")
            continue;
        else if(string(line) == "END")
        {
            v.push_back(temp);
            temp = "";
        }
        else
        {
            temp += string(line);
        }

    }
    for(int i=0; i<v.size(); i++)
        cout<<v[i]<<endl;
}