1

I am parsing a CSV file, which has a known structure of string,int,int,double.

I am writing a function that parses a CSV file line-by-line. I am trying to design it so that it looks something like this:

void foo(const string& csvline){
  std::stringstream csvStream(csvline);
  std::string s; int i1; int i2; double d;
  csvline >> s;
  csvline >> i1;
  csvline >> i2;
  csvline >> d;
}

Is there a way to do this for CSV files?

I know that if they were separated by spaces, this will work out of the box. But what about for a CSV file (or an arbitrary delimiter, for that matter)?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Iliketoproveit
  • 445
  • 6
  • 15
  • 1
    There are ways to do it, for example [`std::getline`](http://en.cppreference.com/w/cpp/string/basic_string/getline) can use an arbitrary character as delimiter, not only newline. ***However*** I really don't recommend you implementing your own CSV parser. Error handling (which is always needed) is not very trivial. And generic CSV files have *many* corner and special cases that makes a simple parser using `std::getline` impossible to use. Please try to find an existing library that handles it for you instead. – Some programmer dude Apr 07 '18 at 15:38
  • See [https://stackoverflow.com/questions/11719538/how-to-use-stringstream-to-separate-comma-separated-strings] – tangoal Apr 07 '18 at 15:42
  • This is just for me, I want to get better at parsing and working with streams. I looked into `std::getline` but It always writes to a string doesnt it? I want my code to look as above, is there a way to do this or am i searching for a unicorn? – Iliketoproveit Apr 07 '18 at 15:42

1 Answers1

5

You cannot specify a delimiter with operator>>. Use std::getline() to read a delimited value into a temp std::string, then use a std::istringstream to parse the string.

void foo(const std::string& csvline)
{
    std::istringstream csvStream(csvline);
    std::string s, tmp;
    int i1, i2;
    double d;

    std::getline(csvStream, s, ',');

    std::getline(csvStream, tmp, ',');
    std::istringstream(tmp) >> i1;

    std::getline(csvStream, tmp, ',');
    std::istringstream(tmp) >> i2;

    std::getline(csvStream, tmp);
    std::istringstream(tmp) >> d;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770