I know how to do this with fgets and strtol , I would like to know how to do this using scanf() (if possible).
As others say, scanf not suitable for this, fgets and strtol is an alternative (although fgets has the disadvantage that it is difficult to detect a 0-byte input and it is impossible to say what was entered after 0-byte if there is one).
For completeness (and if the valid input is an integer followed by a new line):
while(scanf("%d%1[\n]", &n, (char [2]){ 0 }) < 2)
Alternatively, use %n before and after %*1[\n] with assignment suppression. Please note, however (from the Debian man page ):
This is not a conversion, although it can be suppressed with an assignment suppression symbol * . The C standard says, "Executing the %n directive does not increase the assignment counter returned at completion," but the Patch seems to contradict this. It is probably wise not to make any assumptions about the effect of the %n transformations on the return value.
mafso source share