-
Notifications
You must be signed in to change notification settings - Fork 1
1.10 Parsing Comma Separated Data
Ray Fix edited this page May 15, 2013
·
3 revisions
Given a string such as "0,1,200,3,4,5,6" how can you process each element separately?
#include <iostream>
#include <sstream>
void tokenize(const std::string& str)
{
std::istringstream stream(str);
for(std::string value; getline(stream, value, ','); )
{
// process value
}
}
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
}
}