I have a token from strtok()
that I want to convert into and integer and place inside of an array using atoi()
. However, I'm having difficulties.
char string[LMAX];
int array[LMAX];
int number;
char *token = NULL;
int count = 0;
FILE *fp;
fp = fopen("test.txt","r");
while(fgets (string, LMAX, fp) != NULL) {
//Reading the file, line by line
printf("%s", string);
token = strtok(string,",");
array[count++] = atoi(token);
//printf("%d",array[count]);
while(token=strtok(NULL,";,")){
number = atoi(token);
array[count++] = number;
printf("%d",array[count++]);
}
}
number
is of type int
and the array is initialised as an int
array too.
When I run the following code, I get all 0's printed out, but the interesting thing is, when I replace printf("%d", number);
with printf("%d", atoi(token));
, I get the right output. I want to be able to actually store atoi(token) but it is not allowing me to.
Any help is great
EDIT: LMAX = 1024
It's only when I put
array[count++]
in the printf statement that it gives me 0's in the output
This is because count++
has side effects. When you assign array[count++]
and then print array[count++]
, you are not printing the same value, because the second time around the index is incremented.
Moreover, count will be incremented twice, so every other value in the array
would be uninitialized.
If you want to print the value that you have just stored in the array, use count-1
for the index:
while(token=strtok(NULL,";,")){
number = atoi(token);
array[count++] = number;
printf("%d",array[count-1]);
}