My program takes in a string and I break the string into words based on a space, I store the words in an array of pointers. However for some reason it is not separating the words into the appropriate index. In this example and the picture below the text "suspend 0", token1 should correspond to 0 however it corresponds to "end"
int main(){
int ch ,n= 1;
int i = 0;
char str[512], *token[5], *act_token;
while(1){
printf("Enter text: ");
while((ch = getchar()) != '\n')
str[i++] = ch;
str[i] = '\0';
i = 0;
printf("string: %s\n", str);
int spaces = 0;
for(int counter = 0; counter < strlen(str) + 1; counter++){
if(str[counter] == ' '){
spaces++;
}
}
printf("Spaces: %d\n", spaces);
strtok(str, " ");
while(n <= spaces && (act_token = strtok(NULL, " "))){
token[n] = act_token;
n++;
}
token[n] = NULL;
// printf("token[1]: %s\n", token[1]);
for(int x = 1; x < spaces+1; x++){
printf("token[%d]: %s\n", x, token[x]);
}
}
return 0;
}