简体   繁体   中英

Reading data from file

I have .txt file which contains data as follows [12,25],[36,45] ie numbers are enclosed in square brackets separated by comma from each other I want to read such file through C++ program

I referred to string toolkit available,specifically regex facility can be used but i'm not able put in program can someone please help me??

just use scanf or fscanf like this:

if(scanf("[%d,%d]",&a[i],&b[i])==2){
  ++i;
  while(scanf(",[%d,%d]",&a[i],&b[i])==2) ++i;
}

don't forget that CI/O functions are valid C++.

Would I be correct in guessing that those are co-ordinates, if so have you thought about writing a short parser for them? So you could read out a list of vertices?

Alternatively, if your really want to go down the regex path, you might want to look into downloading the boost library, boost.regex works a dream :)

#include <iostream>
#include <iterator>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

bool isSeparator(const char c){
    return c == '[' || c == ']' || c == ',';
}

int main(){
    const char filename[] = "data.txt";

    ifstream fin(filename);
    vector<int> v;
    string buff;
    while(getline(fin, buff)){
        replace_if(buff.begin(), buff.end(), isSeparator, ' ');
        istringstream sin(buff);
        for(int n;sin >> n;){
            v.push_back(n);
        }
    }
    copy(v.begin(), v.end(), ostream_iterator<int>(cout,"\n"));
    //for(int i=0;i<v.size();++i) cout << v[i] << endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM