P_zz 2018-11-13 08:43 采纳率: 54.5%
浏览 2947
已采纳

c++读取与修改文件中的特定数据

图片说明

            下划线部分的内容修改为我要修改的内容,修改的数据长度不确定,
            且保留其他数据不变
  • 写回答

2条回答 默认 最新

  • Italink 2018-11-13 11:39
    关注
    #include<iostream>
    #include<fstream>
    #include<string>
    #include<regex>
    using namespace std;
    int main() {
        string str;
        int count = 0;
        ifstream in("in.txt");
        getline(in, str);       //读取第一行文本
        in.close();
        regex pat("(-\\w{1,} )([\\d\\w]{1,}) ");  //匹配模式
        regex ip("(([01]{0,1}\\d{0,1}\\d|2[0-4]\\d|25[0-5])\\.){3}[01]{0,1}\\d{0,1}\\d|2[0-4]\\d|25[0-5]"); //存储提取到的数据
        smatch matches;                                     //存储匹配到的字符串
        string replacedate[3] = { "00","11","22" };         //假设依此替换成这些数据
        string result;
        while (regex_search(str, matches, pat)) {
            result += matches.prefix();
            result += string(matches[1]) + replacedate[count++] + " ";    //替换数据
            str = matches.suffix();                     //修改剩余的字符串
        }
        result += str;
        result= regex_replace(str, ip, "255.255.255.255");        //替换ip
        ofstream out("in.txt");
        out << result << endl;
        return 0;
    }
    

    图片说明

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?