I want to split a string into tokens and save data into variables. I have the following string:
John|Doe|Melbourne|6270|AU
I need to split it by | and every token keep as variable so I can use them in my program, like:
fname = "John"
lname = "Doe"
city = "Melbourne"
zip = "6270"
country = "AU"
tried this so far, I can access first token the rest I don't know how (besides a while loop that doesn't help me):
#include <stdio.h>
#include <string.h>
int main (void) {
char str[] = "John|Doe|Melbourne|6270|AU";
strtok(str, "|");
printf("%s\n", str);
return 0;
}
                    char fname[32], lname[32], city[32], zip[32], country[32];
    strcpy(fname, strtok(str , "|"));
    strcpy(lname, strtok(NULL, "|"));
    strcpy(city , strtok(NULL, "|"));
    strcpy(zip , strtok(NULL, "|"));
    strcpy(country, strtok(NULL, "|"));
    printf("%s\n", fname);
    printf("%s\n", lname);
    printf("%s\n", city);
    printf("%s\n", zip);
    printf("%s\n", country);
                        If the format is constant, you can use sscanf():
char fname[32], lname[32], city[32], zip[16], country[8];
if(sscanf(str, "%31[^|]|%31[^|]|%31[^|]|%15[^|]%7s",
               fname, lname, city, zip, country) == 5)
{
}
This uses the %[] character set format specifier to grab "everything except a vertical bar". The width is included to prevent buffer overruns.
just keep on calling strtok
char* name = strtok(str, "|");
char* surname = strtok(NULL, "|");
...
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With