strtok

N

New

I have a String from a file in the form <number> <word>,<word>,<word>,<word>
<number>
when I try to tokenize it I store it in a char[] and tokenize it using
strtok(string, " ") and then tokenize the orignal string using
strtok(string,",")

the first tokenization gives me only the first number and then NULL's
and the second tokenization gives me 1st char[]=<word> 2nd char[]=<word> 3rd
char[]=<word>
4th char[]=<word> <number>

What am I doing wrong?
 
D

Dan Pop

In said:
I have a String from a file in the form <number> <word>,<word>,<word>,<word>
<number>
when I try to tokenize it I store it in a char[] and tokenize it using
strtok(string, " ") and then tokenize the orignal string using
strtok(string,",")

the first tokenization gives me only the first number and then NULL's
and the second tokenization gives me 1st char[]=<word> 2nd char[]=<word> 3rd
char[]=<word>
4th char[]=<word> <number>

What am I doing wrong?

The proper sequence of strtok calls for your purpose is:

strtok(string, " ");
strtok(NULL, ",");
strtok(NULL, ",");
strtok(NULL, ",");
strtok(NULL, " ");
strtok(NULL, "");

Consider tokenising the whole string with a single sscanf call.

Dan
 
B

bowsayge

New said to us:
I have a String from a file in the form <number> <word>,<word>,<word>,<word>
<number>
when I try to tokenize it I
[...]

You need to change the delimiters string while you loop over the
tokens:

char str [] = "4116 black,10 feet,stationary,none 18";
char * delim = " ";
char * ptr1 = 0;
char * ptr2 = 0;
int field = 0;
ptr1 = str;
while ((ptr2 = strtok(ptr1, delim))) {
ptr1 = 0;
delim = ",";
if (++field == 4) { delim = " "; }
printf ("token: %s\n", ptr2);
}
 
T

Tim Hagan

bowsayge said:
New said to us:
I have a String from a file in the form <number> <word>,<word>,<word>,<word>
<number>
when I try to tokenize it I
[...]

You need to change the delimiters string while you loop over the
tokens:

char str [] = "4116 black,10 feet,stationary,none 18";
char * delim = " ";
char * ptr1 = 0;
char * ptr2 = 0;
int field = 0;
ptr1 = str;
while ((ptr2 = strtok(ptr1, delim))) {
ptr1 = 0;
delim = ",";
if (++field == 4) { delim = " "; }
printf ("token: %s\n", ptr2);
}

If <word> is a single word, then this will work:

#include <stdio.h>
#include <string.h>

int main(void)
{
char s[] = "123 abc,def,ghi,jkl 456";
char *d = " ,";
char *p = s;
char *t;

printf("string: %s\n", s);
while (t = strtok(p, d))
{
printf("token: %s\n", t);
p = NULL;
}
return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
474,146
Messages
2,570,832
Members
47,374
Latest member
anuragag27

Latest Threads

Top