Reputation: 47
What does
scanf("%[^\n]%*c", s);
and
scanf("%[^\n]", s);
mean?
What is the difference?
Upvotes: 2
Views: 155
Reputation: 12668
scanf("%[^\n]%*c", s);
means to scanf that the field length is provided by an extra parameter in the parameter list, just before the string, so to be correct, it should read as
void f(char *buffer, size_t buffer_sz)
{
scanf("%[^\n]%*c", buffer_sz, buffer);
}
(but I'm afraid that you are going to skip over anything that is not a \n
, which probably is not what you wantk, I think that format is incorrect, as you didn't specify the main letter specifier)
Upvotes: 0
Reputation: 3812
Please see the specifications for scanf
, in particular for the format specifiers.
The first statement, scanf("%[^\n]%*c", s);
, reads any characters into the variable called s
of type char*
until there is a newline character (\n
) in the input. This newline character is not read and will remain in the input. It will append a null-terminator (\0
) to the string read into s
. This concludes the "string reading" part.
The function scanf
will then read any character, which in this case must be the newline character, but will not assign its value to any variable as the asterisk (*
) is the "assignment-suppressing character *".
The second statement, scanf("%[^\n]", s);
, is identical to the first, except that it will leave the newline character in the input.
Note that the standard warnings for using scanf
apply here. This function is tricky to use safely. When reading a string, always include a maximum number of characters to read to avoid buffer overflow attacks. E.g. scanf(%16[^\n]", s
. This will read a maximum of 15 characters, as it does not include the null-terminator.
Upvotes: 1