I am trying to split the string and print the tokens.
int main()
{
char line[255] = \"182930101223, KLA1513\";
char val1[16];
char val2[7];
str
Try this:
#include
#include
int main()
{
char line[] = "182930101223, KLA1513";
char* val1;
char* val2;
val1 = strtok(line, ",");
val2 = strtok(NULL, ",");
printf("%s|%s\n", val1, val2);
return 0;
}
There is no need to strcpy()
the tokens, you can just use char*
; strtok()
will add a closing \0
at the end of each token found.
It's also safer, because you don't need to know the size of the tokens beforehand; and size of your tokens was the problem. If you do need to have the token in their own memory, you can copy them into sufficiently sized strings afterwards.
Note that we can't do:
char* line = "182930101223, KLA1513";
because strtok()
modifies the string, and it's not allowed to modify a literal C string.