0

我是 C++ 新手,我有一个包含以下行的文件:

 ~~ 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??

我想阅读两个单词(开始,结束)之间的内容并删除所有其他分隔符~~!-!??

我试过这段代码:

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

        }

结果很奇怪,根本不是我想要找到的!PS:我不知道如何不考虑分隔符(~~!-!??)!

任何建议,修改或链接请!提前致谢。

4

1 回答 1

0
#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";
    }
}
于 2021-08-23T19:27:57.623 回答