Skip to content

Instantly share code, notes, and snippets.

@trairia
Created January 25, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trairia/5d6ff4c62542b91a9e59 to your computer and use it in GitHub Desktop.
Save trairia/5d6ff4c62542b91a9e59 to your computer and use it in GitHub Desktop.
#include<boost/spirit/include/qi.hpp>
#include<iostream>
#include<complex>
#include<string>
template <typename Iterator>
bool parse_complex(Iterator first, Iterator last, std::complex<double>& c){
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
using qi::double_;
using qi::phrase_parse;
using ascii::space;
double rN = 0.0;
double iN = 0.0;
auto cap_real = [&](double x){rN = x; };
auto cap_img = [&](double x){iN = x; };
bool r = phrase_parse(first, last,
(
'('
>> double_[cap_real]
>> -( ',' >> double_[cap_img])
>> ')'
| double_[cap_real]
),
space);
if (!r || first != last)
return false;
c = std::complex<double>(rN, iN);
return r;
}
int main(){
std::string str("(0.42, 2.5)");
std::complex<double> c;
parse_complex(str.begin(), str.end(), c);
std::cout << c << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment