7

What is the best way to read in a tab delimited file in C++ and store each line as a record? I have been looking for an open source library to help with this, but have been unsuccessful so it looks like I will have to write my own.

Mr. Will
  • 2,298
  • 3
  • 21
  • 27
  • 2
    I was amazed that when I searched for this, I was unable to simply pluck some code from somewhere for such a simple thing. Anyway, I wrote a blog for my solution (based on other answers on Stack Exchange) [C++ Tidbits](http://goo.gl/y0bOVv) – Wybird666 Jul 24 '14 at 15:45

3 Answers3

17
typedef vector<vector<string> > Rows;
Rows rows;
ifstream input("filename.csv");
char const row_delim = '\n';
char const field_delim = '\t';
for (string row; getline(input, row, row_delim); ) {
  rows.push_back(Rows::value_type());
  istringstream ss(row);
  for (string field; getline(ss, field, field_delim); ) {
    rows.back().push_back(field);
  }
}

This will get you started. It doesn't do any checking that each row has the same number of fields, allow for escaping field_delim, etc.

5

There is no problem in using iostreams - you could read each line with getline into string, and then use stringstream on that string to iterate over fields.

EFraim
  • 12,811
  • 4
  • 46
  • 62
0

There are a few libraries listed in wikipedia's article CSV_application_support.

Etienne PIERRE
  • 328
  • 1
  • 4