C++ 我应该用什么来代替 sscanf?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1033207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What should I use instead of sscanf?
提问by Ben Hymers
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?
我有一个 sscanf 解决的问题(从字符串中提取内容)。不过我不喜欢 sscanf,因为它不是类型安全的,而且又旧又可怕。我想聪明一点,使用 C++ 标准库的一些更现代的部分。我应该用什么代替?
回答by Fred Larson
Try std::stringstream
:
#include <sstream>
...
std::stringstream s("123 456 789");
int a, b, c;
s >> a >> b >> c;
回答by AraK
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.
如果您需要更强大的工具来进行更复杂的解析,那么您可以考虑 Regex 甚至 Boost 的 Spirit。
回答by 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.
如果包含,sstream
您将可以访问为字符串提供流的 stringstream 类,这正是您所需要的。Roguewave 有一些关于如何使用它的很好的例子。
回答by iampat
If you really want not to use streams (It's good because of readability), you can use StringPrintf.
如果你真的不想使用流(因为可读性很好),你可以使用 StringPrintf。
You can find its implementation in Folly:
你可以在 Folly 中找到它的实现:
https://github.com/facebook/folly/blob/master/folly/String.h#L165
https://github.com/facebook/folly/blob/master/folly/String.h#L165
回答by joe
fgets or strtol
fgets 或 strtol