Skip to content

Instantly share code, notes, and snippets.

@nkoneko
Last active August 29, 2015 13:57
Show Gist options
  • Save nkoneko/9836276 to your computer and use it in GitHub Desktop.
Save nkoneko/9836276 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 <complex>
namespace
{
namespace qi = boost::spirit::qi;
namespace phoenix = boost::phoenix;
template <typename Iterator>
qi::rule<Iterator,
std::complex<double>(),
boost::spirit::ascii::space_type,
qi::locals<double, double>>
complex_number()
{
return qi::eps [qi::_b = 0.0] >>
(
qi::double_ [qi::_a = qi::_1]
>> -('+' >> qi::double_ [qi::_b = qi::_1]) >> 'i'
| qi::double_ [qi::_a = qi::_1]
) >> qi::eps [qi::_val = phoenix::construct<std::complex<double>>(qi::_a, qi::_b)];
}
}
int main()
{
std::string buffer;
while (getline(std::cin, buffer))
{
if (buffer.empty() || buffer == "bye")
break;
std::complex<double> result;
auto iter = buffer.begin();
if (boost::spirit::qi::phrase_parse(
iter, buffer.end(),
complex_number<decltype(iter)>(),
boost::spirit::ascii::space,
result))
{
std::cout << "real=" << result.read() << std::endl;
<< "imag=" << result.imag() << std::endl;
}
else
{
std::cerr << "Failed to parse" << std::endl;
for (; iter == buffer.end(); ++iter)
std::cerr << *iter;
std::cerr << std::endl;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment