I have a CSV file, with entries like:
1, 1234
2, 67890
3, 123987
...
I want to parse this into a C++ vector where the second column becomes the vector data: e.g. 1234, 67890, 123987 ...
As an experienced C programmer, but a C++ rookie, below is my attempt, which works fine, but uses the much maligned sscanf() function. In perusing stackoverflow.com, I see lots of answers to similar questions with very complicated parsing techniques. For example, the recommended solution to How can I read and parse CSV files in C++? involves creating a row class, and an iterator class, with lots of lines of code. Isn't there something simple, without requiring external libraries, that can do this?
Here's my code:
ifstream myfile (filename);
if (!myfile.is_open()) {
printf ("no file\n");
exit(1);
}
vector<uint32_t> dataVec;
string line;
int val;
while (getline (myfile, line)) {
if (sscanf (line.c_str(), "%*d , %d", &val) == 1) {
dataVec.push_back(val);
count++;
}
}
myfile.close();
So, is there a simple way to do this in purer C++ without using sscanf(), and without using the line.c_str() hack?
Thanks.