Reading a Comma-Separated Text File - C++ File Stream

C++ examples for File Stream:Text File

Description

Reading a Comma-Separated Text File

Demo Code

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

void split(const string& s, char c, vector<string>& v) {
  int i = 0;/*from w w  w  .j a  v a  2  s  .  c om*/
  int j = s.find(c);
  while (j >= 0) {
    v.push_back(s.substr(i, j - i));
    i = ++j;
    j = s.find(c, j);

    if (j < 0) {
      v.push_back(s.substr(i, s.length()));
    }
  }
}

void loadCSV(istream& in, vector<vector<string>*>& data) {
  vector<string>* p = NULL;
  string tmp;

  while (!in.eof()) {
    getline(in, tmp, '\n');

    p = new vector<string>();
    split(tmp, ',', *p);

    data.push_back(p);

    cout << tmp << '\n';
    tmp.clear();
  }
}
int main(int argc, char** argv) {
  ifstream in("data.txt");

  if (!in)
    return(EXIT_FAILURE);

  vector<vector<string>*> data;

  loadCSV(in, data);

  for (vector<vector<string>*>::iterator p = data.begin(); p != data.end(); ++p) {
    delete *p;
  }
}

Related Tutorials