Skip to content

1.10 Parsing Comma Separated Data

Ray Fix edited this page May 15, 2013 · 3 revisions

Problem

Given a string such as "0,1,200,3,4,5,6" how can you process each element separately?

Solution

#include <iostream>
#include <sstream>
void tokenize(const std::string& str)
{
  std::istringstream stream(str);
  for(std::string value; getline(stream, value, ','); )
  {
    // process value
  }
}

Discussion

This method constructs a stream from the string and then uses get line to break the string up. Another solution (possibly more efficient) uses the Boost library.

#include<iostream>
#include<boost/tokenizer.hpp>
#include<string>

void tokenize(const std::string& str)
{
    boost::char_separator<char> sep(",", "", boost::keep_empty_tokens);
    boost::tokenizer<boost::char_separator<char>> tok(str, sep);

    for (auto const& value : tok)
    {
       // process value
    }
}

Also See

Clone this wiki locally