views:

1220

answers:

6

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?

+1  A: 

fgets or strtol

joe
+18  A: 

I think the other answers are missing the point. The question isn't about I/O, it's about extracting data from a string.

Try stringstream:

#include <sstream>

...

std::stringstream s("123 456 789");
int a, b, c;
s >> a >> b >> c;
Fred Larson
+2  A: 

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

Kaleb Pederson
A: 

sscanf is a perfectly fine function to use in C. Combined with fgets, it allows you to parse data without too much work. Don't forget to check its return value and also turn up compiler warnings so you can detect format string to variable type mismatches.

On the other hand, don't use scanf.

Sinan Ünür
+2  A: 

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.

AraK