cstring

What does %[^\n] mean in C?


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;
}

Solution

  • [^\n] is a kind of regular expression.

    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.