I am trying to use getchar()
to read all the digits of an input number and store them in an array. But every time I run the program something goes wrong with the second digit.
Here is my code:
int ch = 0;
int digits[0];
int i = 0;
while ((ch = getchar()) != '\n') {
digits[i] = ch - '0';
i++;
}
To show what will go wrong, I inserted two printf
:
while ((ch = getchar()) != '\n') {
printf("%d ", ch);
digits[i] = ch - '0';
printf("%d\n", ch);
i++;
}
For example, when I input 1100
, I get:
49 49
49 1
48 48
48 48
And when I print the array in a separate loop, the output is:
1 10 0 0
When I input 66666
, I get:
54 54
54 6
54 54
54 54
54 5
And the array is:
6 10 6 6 6
I've tried a bunch of other numbers with different lengths, every time the same weird thing happens with the second digit, and only the second. Does anyone know why's that? Thanks a lot!