从文本文件中读取值并获取有用的部分

问题描述 投票:0回答:1

我想读取一个文本文件,如果itataror在序列中看到age =“,它将在它之后取值直到下一个”,然后复制到另一个文本文件中。要明确一个例子。

input file : 

age="12"
somthing else="39"
age="21"
age=24
age="22"
somthing else="123"

output : 

12
21
24
22

我如何使用fstream编写类似的代码?是否有任何有用的文档或教程视频。

c++ fstream textreader
1个回答
0
投票

似乎是正则表达式的完美用例

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

int main() 
{
    std::regex r{R"~~((.*)="([^"]*)".)~~"}; 
    // match the name and age within the quotes 

    std::ifstream f{"input.txt"};
    std::string line;
    std::smatch m;
    while(std::getline(f, line))
      if (std::regex_match(line, m, r))  // if it matches
        if (m[1].str() != "somthing else") // and name is not something else
          std::cout << m[2].str() << "\n";  // print the age
}
© www.soinside.com 2019 - 2024. All rights reserved.