I\'m taking a part in a challenge, and just to cut to the point, in one of places in my program I need to convert string to an integer. I\'ve tried boost::lexical_cast but u
I can recommend Boost Spirit (parse with Qi):
.
#include
namespace qi = boost::spirit::qi;
const char *demo1 = "1234";
const char *demo2 = "1234,2345,-777,-888";
const char *demo3 = " 1234 , 2345 , -777, -888 ";
void do_demo1()
{
const char *begin = demo1;
const char *iter = begin;
const char *end = demo1+strlen(demo1);
int result;
if (qi::parse(iter, end, qi::int_, result))
std::cout << "result = " << result << std::endl;
else
std::cout << "parse failed at #" << (iter - begin) << ": " << std::string(iter, end) << std::endl;
//// to allow for spaces, use phrase_parse instead of parse
// if (qi::phrase_parse(begin, end, qi::int_, qi::space, result)
//// ... etc
}
void do_demo2()
{
const char *begin = demo2;
const char *iter = begin;
const char *end = demo2+strlen(demo2);
std::vector results;
if (qi::parse(iter, end, qi::int_ % ',', results))
std::cout << "results = " << results.size() << std::endl;
else
std::cout << "parse failed at #" << (iter - begin) << ": " << std::string(iter, end) << std::endl;
}
void do_demo3()
{
const char *begin = demo3;
const char *iter = begin;
const char *end = demo3+strlen(demo3);
std::vector results;
if (qi::phrase_parse(iter, end, qi::int_ % ',', qi::space, results))
std::cout << "results = " << results.size() << std::endl;
else std::cout << "parse failed at #" << (iter - begin) << ": " << std::string(iter, end) << std::endl;
}
int main()
{
do_demo1();
do_demo2();
do_demo3();
return 0;
}
Be sure to look at binary (de)serialization IFF you can dictate the stream (text) format. See my recent answer here for a comparison of methods when aimed at serializing/deserializing:
That post includes benchmarks