c - scanf C程序

标签 c scanf

所以我一直在看一个 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++])) { ... }

  1. scanf 语句应该只返回一个值。 当它得到除“1”以外的任何内容时(例如,“0”,在文件末尾),循环终止。

  2. 该值将写入a[]

  3. 索引 (a[i++]) 在每次循环中递增

  4. 并且,来自 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/

相关文章:

c - 服务器接受许多客户端

c - 如果使用 C 中的位运算,整数中的任何位等于 1,则返回 1

c - 简单的C计算器错误

c - 从函数返回字符串会产生垃圾

c - 如何使用 mbedtls 在 libcurl 中加载 PEM 证书和私钥

c - 将参数传递给函数指针数组

c - 我想通过 shellexecute() 通过变量打开网站,方法是在 c 中为变量分配网址

c - while 中的 EOF 跳出范围

matlab - fscanf 函数的奇怪行为

使用 sscanf 将长十六进制字符串转换为 int 数组