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.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
int main() {
char line[100];
scanf("%[^\n]",line);
printf("Hello,World\n");
printf("%s",line);
return 0;
}
[^\n]
is a kind of regular expression.
[...]
: 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
.Furthermore fscanf
(and scanf
) will read the longest sequence of input characters matching the format.
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.
See also §7.21.6.2 The fscanf function.