I know how this can be done using
fgets
andstrtol
, I would like to know how this can be done usingscanf()
(if possible).
As the other answers say, scanf
isn't really suitable for this, fgets
and strtol
is an alternative (though fgets
has the drawback that it's hard to detect a 0-byte in the input and impossible to tell what has been input after a 0-byte, if any).
For sake of completeness (and assuming valid input is an integer followed by a newline):
while(scanf("%d%1[\n]", &n, (char [2]){ 0 }) < 2)
Alternatively, use %n
before and after %*1[\n]
with assignment-suppression. Note, however (from the Debian manpage):
This is not a conversion, although it can be suppressed with the
*
assignment-suppression character. The C standard says: "Execution of a%n
directive does not increment the assignment count returned at the completion of execution" but the Corrigendum seems to contradict this. Probably it is wise not to make any assumptions on the effect of%n
conversions on the return value.