我应该使用什么来代替 sscanf?

发布于 2024-07-25 19:55:42 字数 112 浏览 1 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

罗罗贝儿 2024-08-01 19:55:42

尝试 std::stringstream

#include <sstream>

...

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

Try std::stringstream:

#include <sstream>

...

std::stringstream s("123 456 789");
int a, b, c;
s >> a >> b >> c;
2024-08-01 19:55:42

对于大多数工作,标准流可以完美地完成工作,

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
}

如果您需要更强大的工具来进行更复杂的解析,那么您可以考虑 Regex 甚至 Boost 的 Spirit。

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.

谈场末日恋爱 2024-08-01 19:55:42

如果包含 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.

静谧 2024-08-01 19:55:42

如果你真的不想使用流(因为可读性很好),你可以使用
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

倾城°AllureLove 2024-08-01 19:55:42

fgets 或 strtol

fgets or strtol

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文