C 中的可变参数 scanf

发布于 2024-11-27 21:33:50 字数 362 浏览 3 评论 0原文

我很好奇是否可以在 C 中实现 scanf 的某种可变版本。我的意思是如果输入是 push (1 2 3), scanf 能够将其解析为 %s %d %d %d ,类似于 scanf("%s (%d)", string, some_list)代码>.

它将获取 %d 的所有实例并将它们(按顺序)附加到列表中......

我说得有道理吗?

编辑:对于指定的输入,string == "push"some_list == [1, 2, 3]

I was curious if it's possible to implement a sort of variadic version of scanf in C. What I mean is if the input is push (1 2 3), scanf would be able to parse that into %s %d %d %d with something like scanf("%s (%d)", string, some_list).

It would take all instances of %d and append them (in order) to the list...

Am I talking sense?

EDIT: For the specified input, string == "push" and some_list == [1, 2, 3].

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

追风人 2024-12-04 21:33:50

vscanf、vssscanf、vsfcanf 不是您要找的吗?它们从 C99 开始可用。

以下是 vscanf 函数。请注意,C 是一种编译型强类型语言,您需要正确给出格式说明符。做类似高级语言所做的事情将涉及更多工作(但这是可能的,因为功能反过来是用 C 编写的)。

Isn't vscanf, vssscanf, vsfcanf is what you are looking for? They are avaialble from C99 onwards.

Here is a decription and example of usage of vscanf function. Note that C being a compiled and a strongly typed language, you need to give format specifiers properly. Doing something like what higher languages dos is going to involve more work (but is possible because features are inturn written in C).

画中仙 2024-12-04 21:33:50

当然。您可以实现一个像这样工作的 scanf 版本。

它不是 C 库的一部分的原因是它需要未内置到库中的数据结构。就像链接列表或可调整大小的数组一样。

但无论如何,您可以创建一个接受高级形式模式的 scanf 函数。它可能看起来像 super_scanf("%{s:allocate} (%{d*:array,append)", &string, &array)

但通常,您要么编写自己的分词器,然后简单的解析器或者你升级到像 lex/yacc 这样强大的东西。或者您可以使用正则表达式库,例如 PCRE 库。

Sure. You could implement a version of scanf that worked like this.

The reason it isn't part of the C library is that it would require data structures that aren't built in to the library. Like a linked-list, or a resizable array.

But anyway, you could make a scanf function that accepted an advanced form of patterns. It could look like super_scanf("%{s:allocate} (%{d*:array,append)", &string, &array)

But normally, you either write your own tokenizer and simple parser or you move up to something powerful like lex/yacc. Or you might use a regular expression library like the PCRE library.

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