-
looping with strtok()
I'm rather stumped on how to use strtok() in loops, it works fine for the first input and then 'dies' out on me for successive ones. Here's what I mean:
Code:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void tok_me()
{
char szString[BUFSIZ];
int index = 0;
char delims[] = " \n";
char *result = NULL;
while ((szString[index] = fgetc(stdin)) != '\n')
index++;
result = strtok(szString,delims);
while (result != NULL)
{
printf("result is \"%s\"\n", result);
result = strtok(NULL,delims);
}
}
int main(int argc, char **argv)
{
tok_me();
tok_me();
tok_me();
return 0;
}
Basically it just breaks up the user input (ended with a \n) three times. I'm just experimenting with it before I put it in my larger program that requires successive tokenising and it has been giving me errors so I just went back to a simpler model (above).
Heres a sample output of the program:
Code:
$ ./token1
something 5 11
result is "something"
result is "5"
result is "11"
different 2
result is "different"
result is "2"
result is "11"
ah
result is "ah"
result is "ferent"
Now I'm not sure what I'm doing wrong! But it seems to use the last strings (or part of it in the 3rd loop). Why does this occur? Doesn't the local variables get pushed off the stack? Or am I missing something here? I've already searched the forums for countless threads with none relating to this and I've already referred to man pages and c books to no avail!
Any help or input would be greatly appreciated! Thanks! :)
-
> while ((szString[index] = fgetc(stdin)) != '\n')
You're missing off the \0 to mark the end of the string.
The fgets() function does exactly what you're trying to do, making sure not to overflow the buffer, and adding a \0 at the end.
Other than that, it looks good.
-
It works nicely now, thanks!
Hopefully It'll work on the larger program :p