What should I use instead of sscanf?

旧巷老猫 提交于 2019-11-28 21:11:04

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.

Kaleb Pederson

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.

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

fgets or strtol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!