-
Arrays and tokens
Hi
I have created the below function to extract tokens from a buffer that has been input via the keyboard (stdin).
e.g.
inbuff: 22 33
A call of: gettoken(' ') will put 22 into the token array.
However I also want it to go onto the next token when the function is called agn.
eg
input: 22 33 44
Call 1: token:= 22
Call 2: token:= 33
Call 3: token:= 44
At the moment all i get is the first token each time when calling gettoken. Any help would be greatly appreciated. Code is shown below.
Code:
char *gettoken(char sep)
{
while ((inbuff[num] !=sep) && (inbuff[num] != '\0') && (inbuff[num] != '\n'))
{
token[num]=inbuff[num];
num++;
}
token[num]='\0';
num++;
return token;
}
-
Try this.
Code:
char *gettoken(char sep)
{
int i = 0;
while ((inbuff[num] !=sep) && (inbuff[num] != '\0') && (inbuff[num] != '\n'))
{
//token[num]=inbuff[num];
token[i++]=inbuff[num];
num++;
}
//token[num]='\0';
token[i]='\0';
num++;
return token;
}
-
You can try this function, to see if it can makes the work:
Code:
#include <stdio.h>
void gettoken(char *inbuf, char *outbuf, char delim)
{
static char *pNext = inbuf; //first points to the string, after to next tokens
int i;
for (i=0; (*pNext != delim) && (*pNext != '\0'); pNext++,i++)
outbuf[i] = *pNext;
//check if we are in last token
if (*pNext++ == '\0')
pNext = inbuf;
outbuf[i] = '\0'; //put null to close string
}
int main(void)
{
char inbuf[] = "One|Two|Three";
char outbuf[100];
int i;
//get first three tokens and print them
for (i=0; i<3; i++)
{
gettoken(inbuf, outbuf, '|');
puts(outbuf);
}
//now check if the function knows how to restart to first token
gettoken(inbuf, outbuf, '|'); //this should put in outbuf 'one'
puts(outbuf);
return 0;
}
It's real simple it contains a static pointer that points to the next token to be getted, if is the last token, it points to the first one again.