Search code examples
cinitializationscanf

Initializing and scanning a variable in C


can anyone please help me out with this in C language for ex:

int a = scanf("%d", &a);

doesn't assign the input value to a, but instead gives zero only always.

but this works as intended:

int a;
int a = scanf("%d", &a);

Solution

  • int a;
    int a = scanf("%d", &a);
    

    Does not compile because you redefine the variable a twice in the same scope.

    scanf("%d", &a) attempts to parse the characters from stdin as the representation of an int and if successful stores the value to a and returns 1, otherwise returns EOF at end of file and 0 if characters are present but do not represent an int value in decimal representation.

    Here is an example:

    #include <stdio.h>
    
    int main() {
        int a, c, res;
        for (;;) {
            res = scanf("%d\n", &a);
            switch (res) {
              case 1:    printf("value input is %d\n", a);
                         break;
              case 0:    printf("input is not a number\n");
                         break;
              case EOF:  printf("end of file detected\n");
                         return 0;
            }
            // read and discard the rest of the input line
            while ((c = getchar()) != EOF && c != '\n')
                continue;
        }
    }