Seek Addo Seek Addo - 1 year ago 81
C Question

scanf with %n giving wrong output

I am reading an Integer with

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

I know this kind of problem with
that is
---> 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
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
for this or is there a way to fix this in
. 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: ");

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


return 0;

enter image description here

Answer Source

%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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download