Search code examples
cscanfformat-specifiers

C - format specifier for scanf?


float lat, lon;
char info[50];

scanf("%f, %f, %49[^\n]", &lat, &lon, info);

In the above snippet, what kind of format specifier is %49[^\n].

I do understand that it is the format specifier for the character array which is going to accept input upto 49 characters (+ the sentinal \0), and [^\n] looks like its a regex (although I had read somewhere that scanf doesn't support regex) OR a character set which is to expand to "any other character" that is NOT "newline" \n. Am I correct?

Also, why is there no s in the format specifier for writing into array info?

The program this snippet is from works. But is this good C style?


Solution

  • The specifier %[ is a different conversion specifier from %s, even if it also must be paired with an argument of type char * (or wchar_t *). See e.g. the table here

    [set] matches a non-empty sequence of character from set of characters.
    If the first character of the set is ^, then all characters not in the set are matched. If the set begins with ] or ^] then the ] character is also included into the set. It is implementation-defined whether the character - in the non-initial position in the scanset may be indicating a range, as in [0-9]. If width specifier is used, matches only up to width. Always stores a null character in addition to the characters matched (so the argument array must have room for at least width+1 characters)