4.23. Reading a Comma-Separated Text File
Problem
You want to read in a text file that is delimited by commas and new lines (or any other pair of delimiters for that matter). Records are delimited by one character, and fields within a record are delimited by another. For example, a comma-separated text file of employee information may look like the following:
Smith, Bill, 5/1/2002, Active Stanford, John, 4/5/1999, Inactive
Such files are usually interim storage for data sets exported from spreadsheets, databases, or other file formats.
Solution
See Example 4-32 for how to do this.
If you read the text into strings one contiguous chunk
at a time using getline (the function template defined
in <string>) you can use the split function I presented in Recipe 4.6 to parse the text and put it in a
data structure, in this case, a vector.
Example 4-32. Reading in a delimited file
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
void split(const string& s, char c,
vector<string>& v) {
int i = 0;
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'); // Grab the next line
p = new vector<string>();
split(tmp, ',', *p); // Use split from
// Recipe 4.7 data.push_back(p); cout << tmp << '\n'; tmp.clear(); } } int main(int ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access