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.
-
2I 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++ TidbitsWybird666– Wybird6662014-07-24 15:45:41 +00:00Commented Jul 24, 2014 at 15:45
Add a comment
|
3 Answers
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.
2 Comments
tumchaaditya
this code does bot work in visual studio. the error is error "C4430: missing type specifier - int assumed". I have included string.h
thaweatherman
Code compiles fine on CentOS with g++. Not sure what you didn't add in to make it work