Skip to content

Instantly share code, notes, and snippets.

@nkoneko
Created March 29, 2014 09:39
Show Gist options
  • Save nkoneko/9851493 to your computer and use it in GitHub Desktop.
Save nkoneko/9851493 to your computer and use it in GitHub Desktop.
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <iostream>
#include <string>
#include <numeric>
namespace client
{
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace phoenix = boost::phoenix;
template <typename Iterator>
const
qi::rule<Iterator,
std::vector<double>(),
ascii::space_type>
parse_nums(const std::string& delim)
{
return qi::eps [qi::_val = phoenix::construct<std::vector<double>>()]
>> qi::double_ [phoenix::push_back(qi::_val, qi::_1)]
>> *(qi::lit(delim) >> qi::double_ [phoenix::push_back(qi::_val, qi::_1)]);
}
}
int main()
{
std::string buffer;
while (std::getline(std::cin, buffer))
{
if (buffer == "bye")
break;
std::vector<double> result;
auto iter = buffer.begin();
if (boost::spirit::qi::phrase_parse(
iter, buffer.end(),
client::parse_nums<decltype(iter)>(","),
boost::spirit::ascii::space,
result))
{
std::cout << "sum = " <<
std::accumulate(
result.begin(),
result.end(),
0.0,
[](const auto& x, const auto& y){ return x + y; })
<< std::endl;
}
else
{
std::cerr << "Failed to parse." << std::endl;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment