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 use some more modern parts of the C++ standard library. What should I use instead?
sscanf() Return value If successful, the sscanf() function returns the number of receiving arguments successfully assigned. If a matching failure occurs before the first receiving argument was assigned, returns zero.
The bug is that `sscanf` (`vsscanf` actually) is very slow on large strings.
The string-based functions, such as sprintf() and sscanf() , do not depend on the stdio library. These functions are thread-safe.
Try std::stringstream
:
#include <sstream> ... std::stringstream s("123 456 789"); int a, b, c; s >> a >> b >> c;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With