I have the following code:
#include <stdio.h>
#include <string.h>
int main (void) {
char str[] = "John|Doe|Melbourne|6270|AU";
char fname[32], lname[32], city[32], zip[32], country[32];
char *oldstr = str;
strcpy(fname, strtok(str, "|"));
strcpy(lname, strtok(NULL, "|"));
strcpy(city, strtok(NULL, "|"));
strcpy(zip, strtok(NULL, "|"));
strcpy(country, strtok(NULL, "|"));
printf("Firstname: %s\n", fname);
printf("Lastname: %s\n", lname);
printf("City: %s\n", city);
printf("Zip: %s\n", zip);
printf("Country: %s\n", country);
printf("STR: %s\n", str);
printf("OLDSTR: %s\n", oldstr);
return 0;
}
Execution output:
$ ./str
Firstname: John
Lastname: Doe
City: Melbourne
Zip: 6270
Country: AU
STR: John
OLDSTR: John
Why can't I keep the old data nor in the str
or oldstr
, what am I doing wrong and how can I not alter the data or keep it?
strtok()
works (it modify string in same address space), I think you should have a look: – Saycestr
before you callstrtok
or don't usestrtok
and use a pair of pointers to bracket and copy each token, or a combination ofstrcspn
andstrspn
to do the same thing. With either of the other methods you can tokenize a string-literal because the original isn't modified, butstrtok
modifies the original by replacing the separator with nul-characters. – Acetylide