C++/Boost: Writing a more powerful sscanf replacement -


i want write function in c++ replace c's sscanf assigns matches iterator.

basically, want like:

string s = "0.5 6 hello"; std::vector<boost::any> any_vector; sscanv(s, "%f %i %s", any_vector); cout << "float: " << any_cast<float>(any_vector[0]); cout << "integer: " << any_cast<integer(any_vector[1]); cout << "string: " << any_cast<string>(any_vector[2]); 

the exact details may vary, idea. ideas implementation?

options far along problems far:

  • std::istringstream: there's no manipulator matching constant expressions
  • boost.regex: not sure if work , seems more complicated necessary this
  • boost.spirit: don't think work dynamically generated format strings , seems more complicated necessary
  • sscanf: work, non-standard, etc, , using require lot of overhead since number of arguments determined @ compile time

what's that?

void sscanf(std::string str,             const std::string& format,             std::vector<boost::any>& result) {   std::string::const_iterator = format.begin();   while (i != format.end())   {     if (*i == '%')     {       ++i; // *i conversion specifier       char specifier = *i;        ++i; // *i next seperator       std::string extract = str.substr(0, str.find(*i));        switch (specifier)        {         // matching integer         case 'i':           result.push_back(boost::lexical_cast<int>(extract));           break;         // matching floating point number         case 'a': case 'e': case 'f': case 'g':           result.push_back(boost::lexical_cast<float>(extract));           break;         // matching single character         case 'c':           result.push_back(boost::lexical_cast<char>(extract));           break;         // matching string         case 's':           result.push_back(extract);           break;         // invalid conversion specifier, throwing exception         default:           throw std::runtime_error("invalid conversion specifier");           break;       }     }     else     {       // if it's not %, eat!       str.erase(0, str.find(*i)+1);       ++i;     }   } } 

some conversions specifiers missing – principally works.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -