What should I use instead of sscanf?

29,960

Solution 1

Try std::stringstream:

#include <sstream>

...

std::stringstream s("123 456 789");
int a, b, c;
s >> a >> b >> c;

Solution 2

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.

Solution 3

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.

Share:
29,960
Ben Hymers
Author by

Ben Hymers

Technical Director at Two Point Studios, a new game developer in the UK. Shipped Two Point Hospital in August 2018. Still working on sim games in Unity and C#. Specialises in AI, game object structure, game architecture, build systems, software engineering practices and C++.

Updated on April 06, 2020

Comments

  • Ben Hymers
    Ben Hymers about 4 years

    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?