Hi I am reading some code and this line has been used:
scanf("%s%*c",dati[i].part);
What does %s%*c do and why not just use %s?
Hi I am reading some code and this line has been used:
scanf("%s%*c",dati[i].part);
What does %s%*c do and why not just use %s?
What does %s%*c do
The %s
has the same meaning as anywhere else -- skip leading whitespace and scan the next sequence of non-whitespace characters into the specified character array.
The %*c
means the same thing as %c
-- read the next input character, whatever it is (i.e. without skipping leading whitespace) -- except that the *
within means that the result should not be assigned anywhere, and therefore that no corresponding pointer argument should be expected. Also, assignment suppression means that scanf
's return value is not affected by whether that field is successfully scanned.
and why not just use %s?
We cannot say for sure why the author of the code in which you saw it used %s%*c
, except for the unsatisfying "because that's what the author thought was appropriate." We have no context at all for making any other judgement.
Certainly the actual effect is to consume the next input character after the string, if any. If there is such a character then it will necessarily be a whitespace character, else it would have been scanned by the preceding %s
directive. We might therefore speculate that the author's idea was to consume a trailing newline.
There are at least two problems with that:
The next character might not be a newline. For example, there might be trailing space characters before a newline, in which case the first of those space characters would be consumed, but the newline would remain in the stream. If that's a genuine problem then %*c
does not reliably solve it.
In practice, it's not very useful. Most scanf
directives are like %s
in that they automatically skip leading whitespace, including newlines. The %*c
serves only to confuse if the next directive that will be processed is any of those. Moreover, it is possible for a scanf
format to explicitly express that a run of whitespace at a given position should be skipped, and it is clearer to make use of that in conjunction with the next directive to be processed if that next directive is one of those that don't automatically skip whitespace (and whitespace skipping is in fact desired).
That doesn't mean that assignment suppression generally or %*c
specifically is useless, mind. It's just trying to use that technique to attempt to consume trailing newlines that is poorly conceived.
The %*
format specifier in a scanf
call instructs the function to read data in the following format (c
in your case) from the input buffer but not to store it anywhere (i.e. discard it).
In your specific case, the %*c
is being used to read and discard the trailing newline character (added when the user hits the Enter
key), which will otherwise remain in the input buffer, and likely upset any subsequent calls to scanf
.