Search code examples
cloopscounterreset

counter getting reset in while loop in C


I am a newbie in programming and taking integer inputs in unsigned character array, using while loop. Somehow the counter is getting auto reset thus making while loop go infinitely.

int i;
unsigned char ab[7];
printf("Enter numbers : ");
i=0;
while(i<7)
{
    scanf(" %d",&ab[i]);
    fflush(stdin);
    i++;
    printf("\nvalue of i : %d",i);
}

By printing counter value , I got to know that counter is getting reset.

Can you suggest what is going wrong and why? And what I can do to make it right?

I am compiling it using gcc version details below.

Apple clang version 13.1.6 (clang-1316.0.21.2.5)
Target: x86_64-apple-darwin21.6.0
Thread model: posix

Thanks


Solution

  • With scanf() %d is for int*, but %hhu assumes unsigned char*.

    I also cleaned up the printf(), and changed the fflush(stdin) to stdout as it makes no sense for stdin.

    #include <stdio.h>
    
    int main () {
            int i;
            unsigned char ab[7];
            printf("Enter numbers : ");
            i=0;
            while(i<7)
            {
                    scanf("%hhu", &ab[i]);
                    i++;
                    printf("value of i : %d\n",i);
                    fflush(stdout);
            }
    
    }
    

    This works:

    % counter
    Enter numbers : 1
    value of i : 1
    2
    value of i : 2
    3
    value of i : 3
    4
    value of i : 4
    5
    value of i : 5
    6
    value of i : 6
    7
    value of i : 7
    %