所以我一直在看一个 C 程序代码,有一段代码让我很困惑。我是 C 的新手,我还没有在 C 中看到任何这样的编码样式。
i = 0;
while (1 == scanf("/%[^/ \t\n]", a[i++]))
printf(">%s<\n", a[i-1]);
最佳答案
您看到的很简单 format string .
在这种情况下:
while (1 == scanf("/%[^/\t\n]", a[i++])) { ... }
scanf 语句应该只返回一个值。 当它得到除“1”以外的任何内容时(例如,“0”,在文件末尾),循环终止。
该值将写入
a[]
。索引 (
a[i++]
) 在每次循环中递增并且,来自 Beej 的指南:
https://beej.us/guide/bgc/output/html/multipage/scanf.html
%[
This is about the weirdest format specifier there is. It allows you to specify a set of characters to be stored away (likely in an array of chars). Conversion stops when a character that is not in the set is matched.
For example, %[0-9] means "match all numbers zero through nine." And %[AD-G34] means "match A, D through G, 3, or 4".
Now, to convolute matters, you can tell scanf() to match characters that are not in the set by putting a caret (^) directly after the %[ and following it with the set, like this: %[^A-C], which means "match all characters that are not A through C."
To match a close square bracket, make it the first character in the set, like this: %[]A-C] or %[^]A-C]. (I added the "A-C" just so it was clear that the "]" was first in the set.)
To match a hyphen, make it the last character in the set: %[A-C-].
So if we wanted to match all letters except "%", "^", "]", "B", "C", "D", "E", and "-", we could use this format string: %[^]%^B-E-].
关于c - scanf C程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40854686/