%[^\n] 在 C 中是什么意思? [英] What does %[^\n] mean in C?
问题描述
%[^\n]
在 C 中是什么意思?我在一个使用 scanf
将多个单词输入输入字符串变量的程序中看到了它.不过我不明白,因为我了解到 scanf 不能接受多个单词.
What does %[^\n]
mean in C?
I saw it in a program which uses scanf
for taking multiple word input into a string variable. I don't understand though because I learned that scanf can't take multiple words.
代码如下:
#include <stdio.h>
#include <stdlib.h>
int main() {
char line[100];
scanf("%[^\n]",line);
printf("Hello,World\n");
printf("%s",line);
return 0;
}
推荐答案
[^\n]
是一种正则表达式.
[...]
:它匹配来自 scanset 的非空字符序列(由...
给出的一组字符).^
表示扫描集是否定的":它由它的补码给出.^\n
:扫描集是除\n
之外的所有字符.
[...]
: it matches a nonempty sequence of characters from the scanset (a set of characters given by...
).^
means that the scanset is "negated": it is given by its complement.^\n
: the scanset is all characters except\n
.
此外,fscanf
(和scanf
)将读取与格式匹配的最长输入字符序列.
Furthermore fscanf
(and scanf
) will read the longest sequence of input characters matching the format.
所以 scanf("%[^\n]", s);
将读取所有字符,直到到达 \n
(或 EOF
>) 并将它们放在 s
中.在 C 中阅读整行是一种常见的习惯用法.
So scanf("%[^\n]", s);
will read all characters until you reach \n
(or EOF
) and put them in s
. It is a common idiom to read a whole line in C.
另请参阅§7.21.6.2 fscanf 函数.
这篇关于%[^\n] 在 C 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!