variadic scanf in C

2019-08-21 23:50发布

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].

2条回答
淡お忘
2楼-- · 2019-08-22 00:14

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).

查看更多
女痞
3楼-- · 2019-08-22 00:35

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.

查看更多
登录 后发表回答