Search code examples
c++stringfileinputstreamifstream

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


I have an input file (.txt) like below -

BEGIN
ABC
DEF
END
BEGIN
XYZ
RST
END

I have to extract everything from BEGIN to END and store them in a string. So, from this file I'll have two strings.

"ABC
DEF"

"XYZ
RST"

I am using ifstream to read the input file. My question is, how can I parse the input file to get everything from one BEGIN to next END. getline() has character as delimiter, not string. Another way I tried was copying everything from the input file to a string and then parse the string based on .find(). However, in this method, I only get the first BEGIN to END.

Is there any way I can store everything in a string from the input file until a certain string appears (END)?

For storing purpose, I am using a vector<string> to store.


Solution

  • Replace filename with a proper name.

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