1

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.

loneRanger
  • 812
  • 1
  • 8
  • 14
  • 1
    Would you prefer simpler solution or prettier c++ solution? If first, I guess `fscanf` still the best option. – Denis Sheremet Feb 09 '18 at 17:31
  • CSV files themselves are not well defined (there's no established standard - and multiple conflicting implementations). So, how would *anything* have a chance to correctly parse them without using some heuristics? That said; some libraries *do* exist that attempt to parse this "CSV thing" (whatever it may be). – Jesper Juhl Feb 09 '18 at 17:33
  • My solution is simple enough, just wondering if there is an equally simple, or simpler, pure C++ solution. – loneRanger Feb 09 '18 at 17:42
  • I would like this not to be marked as duplicate, but not sure how to do this. – loneRanger Feb 09 '18 at 17:53
  • I would like this not to be marked as duplicate, but not sure how to do this. I've edited my question, with an explanation to why the answer to the presumed duplicate post doesn't apply, or at least doesn't provide a simple enough answer. – loneRanger Feb 09 '18 at 18:02
  • `while (myfile >> line >> line) { dataVec.push_back(stoi(line)); }` and you can remove `num` and `val`. – super Feb 09 '18 at 18:56
  • Re: super's comment. While admirably small, it seg faulted for me. – loneRanger Feb 09 '18 at 19:25

0 Answers0