Seek Addo Seek Addo - 1 month ago 18
C Question

scanf with %n giving wrong output

I am reading an Integer with

scanf
and at the same time checking the number of digit read by
scanf
with the format
%n
, the first output is always correct but after that the output increased one more. That is
scanf
reads the last
"\n"
for the second
scanf
.

I know this kind of problem with
scanf
and
char
that is
scanf("%c",&cval)
---> to
scanf(" %c",&cval)
leaving some little space to avoid scanf reading the end of line. but what is with integers?

I have already seen some question here Link here and they all seems to think
scanf()
is
"retarted"
and fget() should always be used.. Is it really so and is it good to avoid it in projects? I mean to void all this kind of bugs and is there a way to prevent this.
Do i have to use
fget()
for this or is there a way to fix this in
scanf()
. All comments are welcome, and thanks for your time. I just want to know if there is a way to fix it, i know how to use %n.

#include <stdio.h>
int main(void) {


int i =0 ,byte_count = 0,val;

printf("Enter a number: ");

scanf("%d%n",&val,&byte_count);
while (i < 3){
printf("byte count is: %d\n",byte_count);


scanf("%d%n",&val,&byte_count);
i++;
}

return 0;
}


enter image description here

Answer

%n captures all the characters processed by scanf including leading whitespace. Using %n twice can correct that. The format string skips leading whitespace and then gets the beginning count of characters. Then the integer is scanned and finally the total count of characters is captured. The difference in the count is the characters in the integer.
Always check the return of scanf as the input stream may need cleaning.

    int begin = 0;
    int end = 0;
    int val = 0;
    int clean = 0;
    int result = 0;

    do {
        if ( ( result = scanf(" %n%d%n",&begin,&val,&endn)) != 1) {// scan one int
            while ( ( clean = getchar ( )) != '\n') {//clean bad input
                if ( clean == EOF) {
                    fprintf ( stderr, "problem reading input\n");
                    exit ( 1);
                }
            }
        }
        else {//scanf success
            printf("byte count is: %d\n",end-begin);
        }
    } while ( result != 1);
Comments