views:

35

answers:

2

I hear that spirit is really fast at converting string to int.

I am however unable to create a simple function that can do so. Something like

int string_to_int(string& s) { /*?????*/ }

Can anybody use boost spirit to fill in this function.

By the way I am working on boost 1.34 and not the latest version.

+2  A: 

int i = boost::lexical_cast<int>(str);

Alexey Malistov
I've read on a couple occasions that boost::lexical cast is really slow for such trivial conversions. See also http://stackoverflow.com/questions/1250795/very-poor-boostlexical-cast-performance
Ralf
+2  A: 

There are several ways to achieve this:

#include <boost/spirit/include/parse.hpp>
#include <boost/spirit/include/qi_numeric.hpp>

using namespace qi = boost::spirit::qi;

std::string s("123");
int result = 0;
qi::parse(s.begin(), s.end(), qi::int_, result);

or a shorter:

qi::parse(s.begin(), s.end(), result);

which is based on Spirit's auto features. If you wrap one of these into a function, you get what you want.

EDIT: I saw only now that you're using Boost 1.34. So here is the corresponding incantation for this:

#include <boost/spirit.hpp>

using namespace boost::spirit;

std::string s("123");
int result = 0;
std::string::iterator b = s.begin();
parse(b, s.end(), int_p[assign_a(result)]);
hkaiser
Thanks. I see in my profiler that its about 2.5X faster than atoi.
rahul