-1

I have seen the following code work:

int d1, d2, d3, d4, d5;
printf("Enter group of five digits: ");
scanf("%1d%1d%1d%1d%1d", &d1, &d2, &d3, &d4, &d5);

But the following code fail:

int ar[5], counter = 0;
printf("Enter number: ");
while(counter < 5){
    scanf("%1d", &ar[counter]);
    counter++;
}

The digits in the failing code are all 32767. Why is this?

Edit: I have just given a code fragment here. I am trying the the exercise problems in K.N.King's C Programming: A Modern Approach

I saw the second code fragment failing by printing out the array contents one by one.

Seeing a lot of negative responses here, without any explanation as to how I should structure my question isn't helping at all. Also, I'm sure there are alternative approaches to this, but I'm only asking why the second code fragment is failing in the first case.

Edit 2: As input i am entering a 5 digit number followed by enter key: say 12345\n. In the first fragment, 1 is stored in d1, 2 is stored in d2 and so on.

In the second code fragment ar[0] is 32767 instead of 1 and so on. So it fails.

kchak
  • 7,570
  • 4
  • 20
  • 31

1 Answers1

0

Try this:

#include <stdio.h>
#include <conio.h>

int main(int argc, char *argv[]) {
    printf("Enter group of five digits: ");
    char number[5];
    scanf("%s", &number);

    int digits[5];
    for (int i = 0; i < 5; i++) {
        digits[i] = number[i] - '0';
    }

    printf("d1=%d d2=%d d3=%d d4=%d d5=%d", digits[0], digits[1], digits[2],
           digits[3], digits[4]);
    getch();
}
BPL
  • 9,632
  • 9
  • 59
  • 117