Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should I use instead of sscanf?

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?

like image 284
Ben Hymers Avatar asked Jun 23 '09 15:06

Ben Hymers


People also ask

What happens if sscanf fails?

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.

Is sscanf slow?

The bug is that `sscanf` (`vsscanf` actually) is very slow on large strings.

Is sscanf thread safe?

The string-based functions, such as sprintf() and sscanf() , do not depend on the stdio library. These functions are thread-safe.


2 Answers

Try std::stringstream:

#include <sstream>  ...  std::stringstream s("123 456 789"); int a, b, c; s >> a >> b >> c; 
like image 194
Fred Larson Avatar answered Oct 02 '22 23:10

Fred Larson


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.

like image 34
Khaled Alshaya Avatar answered Oct 02 '22 21:10

Khaled Alshaya