Question

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.

Was it helpful?

Solution

There are several ways to achieve this:

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

namespace qi = boost::spirit::qi;

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

or a shorter:

#include <boost/spirit/include/qi_parse.hpp>
#include <boost/spirit/include/qi_numeric.hpp>
#include <boost/spirit/include/qi_auto.hpp>    
namespace qi = boost::spirit::qi;

std::string s("123");
int result = 0;
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)]);

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top