我应该使用什么来代替 sscanf?
我有一个 sscanf 解决的问题(从字符串中提取内容)。 但我不喜欢 sscanf,因为它不是类型安全的,而且又旧又可怕。 我想要聪明一点,使用 C++ 标准库的一些更现代的部分。 我应该用什么来代替?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试
std::stringstream
:Try
std::stringstream
:对于大多数工作,标准流可以完美地完成工作,
如果您需要更强大的工具来进行更复杂的解析,那么您可以考虑 Regex 甚至 Boost 的 Spirit。
For most jobs standard streams do the job perfectly,
If you need more powerful tools for more complex parsing, then you could consider Regex or even Spirit from Boost.
如果包含 sstream,您将可以访问为字符串提供流的 stringstream 类,这正是您所需要的。 Roguewave 有一些很好的 如何使用它的示例.
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.如果你真的不想使用流(因为可读性很好),你可以使用
StringPrintf。
你可以在 Folly 中找到它的实现:
https://github.com /facebook/folly/blob/master/folly/String.h#L165
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 或 strtol
fgets or strtol