Search code examples
c++codeblocksfstreamsqlline

how to read content in a .txt file that is limited by two words in C ++


I am new with C++, I have a file that contains the following lines:

 ~~ 13!-!43??
CaKnX5H83G
 ~~ 107!-!22??
 ~~ 140!-!274??
 ~~ 233!-!75??
begin
 ~~ 143!-!208??
143
 ~~ 246!-!138??
 ~~ 79!-!141??
vC5FxcKEiN
 ~~ 60!-!201??
83
end
 ~~ 234!-!253??
 ~~ 51!-!236??

I want to read the content between the two words (begin, end) and remove all other separators ~~ !-! ??

I tried this code:

#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ifstream my_file;
    my_file.open("file.txt", ios::in);

    if (!my_file) {
        cout << "No such file";
    }
    else {
        string ch;
        string qlline;
        while (1) {
            getline(my_file, qlline);
            if (my_file.eof()) {break;}
            if (qlline.find("end") == 0) {break;}
            if (qlline.find("begin") != 0) {continue;}
            my_file >> ch;
            cout << ch;

        }

The result is strange and not at all what I wanted to find! P.S: I don't know how not to take the separators (~~! -! ??) into consideration!

Any suggestion, modification, or a link please! Thanks in advance.


Solution

  • #include <iostream>
    #include <fstream>
    
    int main()
    {
        std::ifstream my_file("file.txt");
    
        if (!my_file) {
            std::cout << "No such file";
            exit(1);
        }
    
        std::string qlline;
        bool insideSection = false;
        while (getline(my_file, qlline))
        {
            // I have correctly read a line from the file.
            // Now check for boundary markers.
    
            if (qlline.find("end") == 0)   {insideSection = false;break;}
            if (qlline.find("begin") == 0) {insideSection = true; continue;}
    
            // Are we inside the section of the file I want.
            if (!insideSection) {
                continue;
            }
    
            // I am now inside the part of the file with
            // text I want.
            std::cout << qlline << "\n";
        }
    }