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;
}
