C++ equivalent of sscanf?
I've been using sscanf
and I think I've gotten too comfortable with it. Apparently it is deprecated too and I should use sscanf_s
, which is not standard as far as I know. So I was wondering if the ST开发者_JAVA技巧L has an idiomatic C++ replacement do the same thing?
Thanks
I do:
sscanf(it->second->c_str(),"%d %f %f %f %f %f %f %d \" %[^\"] \" \" %[^\"]",
&level, &x, &y, &angle, &length, &minAngle, &maxAngle, &relative, name,parentName);
The formatting isn't as easy but check out stringstream
. See also istringstream
and ostringstream
for input and output buffers formatting.
In C++, the ultimate parser is Boost.Qi
#include <boost/spirit/include/qi.hpp>
#include <string>
namespace qi = boost::spirit::qi;
int main()
{
int level, relative;
float x, y, angle, length, minAngle, maxAngle;
std::string name, parentName;
std::string input = "20 1.3 3.7 1.234 100.0 0.0 3.14 2 \"Foo\" \"Bar\"";
std::string::iterator begin = input.begin();
std::string::iterator end = input.end();
using qi::int_;
using qi::float_;
using qi::char_;
using qi::lit;
using qi::ascii::space;
qi::phrase_parse(begin, end,
int_ >> float_ >> float_ >> float_ >> float_ >> float_ >> float_ >> int_
>> lit("\"") >> *(~char_('"')) >> lit("\"")
>> lit("\"") >> *(~char_('"')) >> lit("\""),
space,
level, x, y, angle, length, minAngle, maxAngle, relative, name, parentName);
}
You can try using stringstream. It is much more powerful than sscanf and serves the purpose.
I believe stringstreams are what you are looking for.
for example:
stringstream tokenizer;
string str("42");
int number;
tokenizer << string;
tokenizer >> number;
If you're using a compiler with enough C++0x support, it's easy to write a type-safe scanf()-style
function... have a read of the printf()
example at http://en.wikipedia.org/wiki/C%2B%2B0x to get you started....
精彩评论