C++处理文本

1、使用sstream版本

(1)功能:截取第一列为1以后的数据,如下图,截取第5行(包括第5行)以后的数据,前面4行数据丢弃。

(2)代码:textProc.cc

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

using namespace std;

int main(int argc, char *argv[]) {// *argv[] 是一个指针数组,也就是一个字符串数组。
    string dir = "/data/";

    string old_file = dir + argv[1] + "/input/txdsp_input_old.dat";
    string gen_file = dir + argv[1] + "/input/txdsp_input.dat";
    string cmd      = "mv ";
    cmd             = cmd + gen_file + " " + old_file;

    if(system(cmd.c_str()) == 0) {
        cout<<"file move ok !"<<endl;
    } else {
        cout<<"file move failed !"<<endl;
    }

    ifstream is(old_file);
    ofstream os(gen_file);
    istringstream iss;
    string line, word;

    while(getline(is, line)) {
        iss.str(line);          // 刷新string流中的字符串
        iss.clear();            // 清除string流中的状态,如果string流读完了failbit会拉起,导致刷新了新数据也不能读取。
        iss>>word;              // 利用string流一个一个单词的读取, 这里只读一个帧头标识。

        if(word == "1") {       // 将找到帧头后的所以数据都输出。
            os<<line<<endl;
            break;
        }
    }

    while(getline(is, line)) {
        os<<line<<endl;
    }

    os.close();
    is.close();
    return 0;
}

 2、regex版本

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

using namespace std;

int main(int argc, char *argv[]) {// *argv[] 是一个指针数组,也就是一个字符串数组。
    string dir = "/data/";

    string old_file = dir + argv[1] + "/input/txdsp_input_old.dat";
    string gen_file = dir + argv[1] + "/input/txdsp_input.dat";
    string cmd      = "mv ";
    cmd             = cmd + gen_file + " " + old_file;

    if(system(cmd.c_str()) == 0) {
        cout<<"file move ok !"<<endl;
    } else {
        cout<<"file move failed !"<<endl;
    }

    ifstream is(old_file);
    ofstream os(gen_file);
    string line;
    smatch results;

    regex re("^1.*");
    while(getline(is, line)) {
        if(regex_search(line, results, re)) {       // 将找到帧头后的所以数据都输出。
            os<<line<<endl;
            break;
        }
    }

    while(getline(is, line)) {
        os<<line<<endl;
    }


    regex re2("^tel:(\\d{11}),addr:(\\w+)");        // 正则表达式相对于python的要多加一个反斜杠“\”,应该\在C是特殊字符
    string str = "tel:15688886666,addr:sichuan";
    regex_search(str, results, re2);                //传给regex_search的字符串可以是string,char,wchar等4种类型,对应的使用smatch,cmatch、wcmatch等4中类型。为了简单,一般只使用string+smatch。
    cout<<results.str()<<endl;               //打印整个str
    cout<<results.str(1)<<endl;                 //打印第一个匹配的括号(\\d{11})
    cout<<results.str(2)<<endl;                  //打印第二个匹配的括号(\\w+)

    os.close();
    is.close();
    return 0;
}

输出:

猜你喜欢

转载自www.cnblogs.com/yuandonghua/p/11871277.html