Reputation: 1664
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
char *strArray[40];
void parsing(char *string){
int i = 0;
char *token = strtok(string, " ");
while(token != NULL)
{
strcpy(strArray[i], token);
printf("[%s]\n", token);
token = strtok(NULL, " ");
i++;
}
}
int main(int argc, char const *argv[]) {
char *command = "This is my best day ever";
parsing(command); //SPLIT WITH " " put them in an array - etc array[0] = This , array[3] = best
return 0;
}
Here it is my code, is there any simply way to solve it? By the way my code is not working. Im new at coding C language and i dont know how can i handle it :( Help
Upvotes: 1
Views: 93
Reputation: 1664
I've done it with your helps, thank you all :)
Its my split library = https://goo.gl/27Ex6O
Codes are not dynamic, if you enters 100 digit input, it will crash i guess
we can use the library with these argument :
parsing (outputfile,inputfile,splitcharacter)
THANKS
Upvotes: 0
Reputation: 40145
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strArray[40];
void parsing(const char *string){//Original does not change
int i = 0;
strArray[i++] = strdup(string);//make copy to strArray[0]
char *token = strtok(*strArray, " ");
while(token != NULL && i < 40 - 1){
strArray[i++] = token;
//printf("[%s]\n", token);
token = strtok(NULL, " ");
}
strArray[i] = NULL;//Sentinel
}
int main(void){
char *command = "This is my best day ever";
parsing(command);
int i = 1;
while(strArray[i]){
printf("%s\n", strArray[i++]);
}
free(strArray[0]);
return 0;
}
int parsing(char *string){//can be changed
int i = 0;
char *token = strtok(string, " ");
while(token != NULL && i < 40){
strArray[i] = malloc(strlen(token)+1);//Ensure a memory for storing
strcpy(strArray[i], token);
token = strtok(NULL, " ");
i++;
}
return i;//return number of elements
}
int main(void){
char command[] = "This is my best day ever";
int n = parsing(command);
for(int i = 0; i < n; ++i){
printf("%s\n", strArray[i]);
free(strArray[i]);
}
return 0;
}
Upvotes: 2
Reputation: 134336
strtok()
actually modify the supplied argument hence you cannot pass a string literal and expect it to work.
You need to have a modifiable argument to get this working.
As per the man page
Be cautious when using these functions. If you do use them, note that:
These functions modify their first argument.
These functions cannot be used on constant strings.
FWIW, any attempt to modify a string literal invokes undefined behavior.
Upvotes: 1