So I'm trying to store int values that have been read from the keyboard into an array of integers in C. Sample user input:
8 99 5 7 8
variable declarations:
int k;
int size;
char buf[100];
The above is my buffer and other variables for the array. The below is to read the ints into the buffer.
printf("Please enter in the numbers for the array:\n");
fgets(buf, 100, stdin);
buf[strlen(buf) - 1] = '\0';
size = (strlen(buf)/2)+1;
int *array = (int *)malloc(sizeof(int)*size);
So that correctly allocates my array.
int i, j;
for(i = 0, j = 0; i < size; i++, j = j+2)
{
array[i] = buf[j] - '0';
}
The above code actually works, but not for numbers that have double digits, only for numbers below 10 and above 0. How can I fix my code so that I correctly read in the integers?
I have tried to do a for
loop with sscanf
, but that just leads to an array with only the first integer entered in all elements.