Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ equivalent of sscanf?

Tags:

c++

stl

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 STL 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);
like image 929
jmasterx Avatar asked May 24 '11 01:05

jmasterx


People also ask

What is sscanf in C?

The sscanf() function reads data from buffer into the locations that are given by argument-list. Each argument must be a pointer to a variable with a type that corresponds to a type specifier in the format-string.

What library is sscanf in C?

The C library function int sscanf(const char *str, const char *format, ...) reads formatted input from a string.

What is the difference between scanf and sscanf?

The scanf function reads data from standard input stream stdin into the locations given by each entry in the argument list. The argument list, if it exists, follows the format string. The sscanf function reads data from buffer into the locations given by argument list.


2 Answers

The formatting isn't as easy but check out stringstream. See also istringstream and ostringstream for input and output buffers formatting.

like image 130
dee-see Avatar answered Nov 16 '22 00:11

dee-see


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);
}
like image 36
xDD Avatar answered Nov 16 '22 01:11

xDD