Storing Value of strtok
Author |
Message |
rar
|
Posted: Sun Mar 07, 2010 7:18 pm Post subject: Storing Value of strtok |
|
|
So I'm trying to use the strtok() function to tokenize a string and store the values inside another array. Also, it happens to be using structures.
However, I'm running into a segmentation fault as soon as the program begins. Here is where I think it lies:
code: |
int count;
for (count = 1; InputString != " done"; count++)
{
ptr = strtok(NULL, " ");
strcpy(WordList[count].Word, ptr);
}
|
The sentence input is:
"the cat in the hat jumped over the lazy fox done"
Done is supposed to end the sentence, not be included in the output. How do I go about storing the tokens? |
|
|
|
|
|
Sponsor Sponsor
|
|
|
chrisbrown
|
Posted: Sun Mar 07, 2010 7:28 pm Post subject: RE:Storing Value of strtok |
|
|
From this site:
"A null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended."
Do you ever call strtok with a string instead of NULL? If not, it might be expecting a string the first time through. |
|
|
|
|
|
DtY
|
Posted: Sun Mar 07, 2010 7:48 pm Post subject: RE:Storing Value of strtok |
|
|
InputString != " done"
Remember, in C, strings are arrays, and arrays are pointers. When you use a comparison operator on them, it will compare the address of the strings.
What you want to use is the function strcmp() to determine if two strings are equal, it will return zero if they are. |
|
|
|
|
|
rar
|
Posted: Sun Mar 07, 2010 9:38 pm Post subject: Re: Storing Value of strtok |
|
|
code: |
struct WordStruct
{
char Word[51];
int length;
}WordList[25];
//main starts here
char InputString[] = "the cat in the hat jumped over the lazy fox done";
char *ptr;
char done[] = "done";
ptr = strtok(InputString, " ");
strcpy(WordList[0].Word, ptr);
int count;
for (count = 1;strcmp(InputString,done); count++)
{
ptr = strtok(NULL, " ");
strcpy(WordList[count].Word, ptr);
}
system("pause");
return 0;
|
There is my code. I had made the strcmp() change before reading your post, having been advised by my professor. Also, I had already used the first call of strtok() with the string.
I'm still getting a segmentation fault. Let it be known that I now despise segmentation faults with a huge passion. |
|
|
|
|
|
chrisbrown
|
Posted: Sun Mar 07, 2010 10:03 pm Post subject: RE:Storing Value of strtok |
|
|
When using strcmp, you want to compare done and ptr, instead of done and InputString (which never changes). |
|
|
|
|
|
rar
|
Posted: Sun Mar 07, 2010 10:48 pm Post subject: RE:Storing Value of strtok |
|
|
Yes, a friend told me this just a few short minutes ago. My program works almost perfectly now. Thanks! |
|
|
|
|
|
|
|