What should I use instead of sscanf?

后端 未结 5 2016
南笙
南笙 2020-12-14 16:17

I have a problem that sscanf solves (extracting things from a string). I don\'t like sscanf though since it\'s not type-safe and is old and horrible. I want to be clever and

相关标签:
5条回答
  • 2020-12-14 16:45

    If you include sstream you'll have access to the stringstream classes that provide streams for strings, which is what you need. Roguewave has some good examples on how to use it.

    0 讨论(0)
  • 2020-12-14 16:45

    fgets or strtol

    0 讨论(0)
  • 2020-12-14 16:46

    For most jobs standard streams do the job perfectly,

    std::string data = "AraK 22 4.0";
    std::stringstream convertor(data);
    std::string name;
    int age;
    double gpa;
    
    convertor >> name >> age >> gpa;
    
    if(convertor.fail() == true)
    {
        // if the data string is not well-formatted do what ever you want here
    }
    

    If you need more powerful tools for more complex parsing, then you could consider Regex or even Spirit from Boost.

    0 讨论(0)
  • 2020-12-14 16:50

    If you really want not to use streams (It's good because of readability), you can use StringPrintf.

    You can find its implementation in Folly:

    https://github.com/facebook/folly/blob/master/folly/String.h#L165

    0 讨论(0)
  • 2020-12-14 16:58

    Try std::stringstream:

    #include <sstream>
    
    ...
    
    std::stringstream s("123 456 789");
    int a, b, c;
    s >> a >> b >> c;
    
    0 讨论(0)
提交回复
热议问题