如何C++抽取txt中某指定内容并保存到另外一个txt中?
怪我咯
怪我咯 2017-04-17 11:48:06
[C++讨论组]

A文件中,内容是这样的:

[fullText]abcd[rating]
[fullText]efg[rating]

我想要抽取[fullText] [rating]之间的内容,并将其保存到B文件中,
不同标签对的内容用空格隔开。
应该怎么写呢?

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(2)
天蓬老师

用正则表达式就几行程序而已:

#include <iostream>
#include <regex>
int main() {
    std::regex r("\\[fullText\\](.*)\\[rating\\]");
    std::string l;
    while(std::cin) {
        std::getline(std::cin, l);
        std::cout << std::regex_replace(l, r, "$1\n");
    }
}

如果你不纠结一定要用C++,那可以更短:

perl -pe 's/\[fullText\](.*)\[rating\]/$1/g'
PHPz

逻辑很简单,知道一点字符串操作和文件操作就好。下面的代码可以实现你的要求,没有考虑异常处理,也没有过多考虑效率,需要的话你自己改改就好

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class Solution {
 public:
  int ProcessFile(const string &src_file, 
                  const string &dest_file,
                  const string &head, 
                  const string &end) {
    ifstream input(src_file.c_str(), ifstream::in);
    if (!input) {
      return -1;
    }
    ofstream output(dest_file.c_str(), ofstream::out);
    if (!output) {
      return -1;
    }
    string line;
    string ::size_type head_len = head.length();
    while(getline(input, line)) {
      string::size_type head_pos = line.find(head, 0);
      string::size_type end_pos = line.find(end, head_pos + head_len);
      output << line.substr(head_pos + head_len, 
                            end_pos - head_pos - head_len) << ' ';
    }
    input.close();
    output.close();
    return 0;
  }
};
int main() {
  string src_file = "input.txt", dest_file = "output.txt";
  string head_name = "[fullText]", end_name = "[rating]";
  Solution sln;
  if (sln.ProcessFile(src_file, dest_file, head_name, end_name) < 0) {
    cout << "Fail..." << endl;
  } else {
    cout << "Success..." << endl;
  }
  return 0;
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号