C language: scanf and sscanf expressions

Viewed 147

I've encountered a expressions that go something like this inside scanf and sscanf arguments:

sscanf(buffer, "%d,%100[^,]%*c%f", destination_pointer)

or

scanf("\n%99s", destination);

What is the correct way of interpreting these? I know what things like "%s %c %d" are, and also that the %100 or generally "%number" is the size of the input to be read. But what about the rest? All I can find are basic examples, nothing near this complex. Is there any reference guide?

1 Answers

What is the correct way to interpreted these?

sscanf(buffer, "%d,%100[^,]%*c%f", destinantion_pointer)

Is an invalid call. There are 3 conversion specifiers that need an argument - %d, %[], %f. That means exactly 3 arguments after formatting string are needed, but only one destinantion_pointer is provided.

  • %d - ignore any whitespace characters, read an int in base 10
  • , - read a comma
  • %100[^,] - read maximum number of 100 characters that are not a comma. Maximum up to 101 bytes (100 characters + null byte) are stored in destination buffer.
    • %[set] - reads characters in the set
    • %[^set] - reads characters that are not in the set
  • %*c - ignore one character (a comma, because %100[^,] reads up until a comma, or the string has ended, which would make scanf return here). Note - ignoring the result of conversion with * makes scanf not increment the return value in the case reading was successful.
  • %f - ignore any whitespace characters, read a float (in any format - decimal, scientific or hexadecimal)

scanf("\n%99s", destinantion);

  • \n - read (and ignore) any number of whitespace characters (whitespace, means anything for that isspace() returns nonzero, so either space, form feed, line feed, carriage return, tab or vertical tab)
  • %99s - ignore any leading whitespace characters (\n in front of it is useless...), then read up to 99 characters that are not whitespaces (the resulting buffer has to be at least 100 bytes long).
Related