Ben*_*ers 26 c++ scanf c++-standard-library
我有一个sscanf解决的问题(从字符串中提取东西).我不喜欢sscanf,因为它不是类型安全的,而且是古老而可怕的.我想要聪明并使用C++标准库的一些更现代的部分.我应该用什么呢?
Fre*_*son 38
#include <sstream>
...
std::stringstream s("123 456 789");
int a, b, c;
s >> a >> b >> c;
Run Code Online (Sandbox Code Playgroud)
对于大多数工作,标准流完美地完成工作,
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
}
Run Code Online (Sandbox Code Playgroud)
如果你需要更强大的工具来进行更复杂的解析,那么你可以考虑Regex甚至是Boost中的Spirit.