ifstream读取文件和stringstream读取内容

使用ifstream读取文件,使用stringstream根据空白切割字符串。

例子一

char str_name[30];
    sprintf(str_name, "%06d.txt", IndFrame);
    string str_name2(str_name);
    string file_path = "/home/ychen/ORB_SLAM2/dataset/kitti_vo/" + str_name2;
    cout << file_path << endl;
    ifstream fin(file_path);
    stringstream ss;
    while(!fin.eof()) {
        char line_1[256];
        fin.getline(line_1,sizeof(line_1));
        string line_2 = line_1;
        if(line_2 == "") continue;
        float f;
        ss << line_2;
        while(ss >> f) {
            cout << f << "  ";  
        }
        ss.str("");
    }
    fin.close();

例子二

ifstream fin("/Users/test.txt");
    if(fin.is_open()){
        vector<vector<string>> dataset_all; // all dataset
        vector<string> vocabulary;          // vocabulary set
        vector<vector<int>> onehot;         // onehot set
        vector<vector<double>> TF;          // TF set
        vector<double> IDF;                 // IDF set
        vector<vector<double>> TFIDF;       // TF_IDF set
        vector<vector<int>> A;              // A set is first half of the smatrox
        vector<vector<int>> B;              // B set is second half of the smatrix

        int td=0, md=0, nd=0;

        while(!fin.eof()){
            char line_1[256];
            fin.getline(line_1,sizeof(line_1));
            string line_2 = line_1;
            if(line_2=="") break; // to delete the null string

            string line_3;
            int count_t=0;
            int count_s=(int)line_2.length()-1;

            // after two tap is the string that we need
            for (int i=0; i<line_2.length(); i++) {
                if(line_2[i]=='\t'){
                    count_t++;
                    // to get the string that we need
                    if(count_t==2){
                        count_s=i;
                        break;
                    }
                }
            }
            line_3 = line_2.substr(count_s+1,(line_2.length()-count_s));
            vector<string> dataset_line;        // the dataset in the every line
            stringstream str(line_3);
            string word;

            while (str >> word) {
                dataset_line.push_back(word);
                // to get the vocabulary set
                if(find(vocabulary.begin(),vocabulary.end(),word) == vocabulary.end()){
                    vocabulary.push_back(word);
                }
            }
            dataset_all.push_back(dataset_line);

            md = (int)dataset_all.size();
            nd = (int)vocabulary.size();
        }
        fin.close();
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值