Parse a list of numbers without hard coding size

Alec Jacobson

March 19, 2015

weblog/

I've been used to parsing numbers from strings with the c-style sscanf function. So if I need to read in 3 floats into a vector I'd use something like:

vector<float> v(3);
sscanf(string_to_parse,"%f %f %f",&v[0],&v[1],&v[2]);

This is fine if you know at compile time that the vector will be size 3. But if the number isn't known at compile time, the c-style gets messy with loops.

Here's a c++-style solution. Admittedly there are also some messy-looking loops, but I still prefer it. It also makes it easy to have a richer delimiter set.

// http://stackoverflow.com/a/1894955
#include <vector>
#include <string>
#include <sstream>
...
  using namespace std;
  vector<double> vect;
  string delimeters = ", ";
  stringstream ss(string_to_parse);
  double v;
  while(ss >> v)
  {
    vect.push_back(v);
    while(string::npos != delimeters.find(ss.peek()))
    {
      ss.ignore();
    }
  }