I am having serious problems attempting to use strtok, I've been staring at the following for hours and cannot figure out why null is showing up everywhere.
I'm using strtok to parse out all words from a string using a space as the delimitor. The first iteration works perfectly, the second iteration and those that follow always have (null) after the first word is parsed.
The second iteration and those that follow should have more than one word, for some reason, only the first word is present from the second iteration and those that follow.
I've attached a screenshot of my output.
http://www.wjdev.net/problem.JPG
Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void encode(char msg[], int key);
void reverse(char msg[]);
int main()
{
int iteration = 0;
char code[] = ".kmpeqgf dmqz szupzq ziafziap zu ezaufmgfue kozqsdqyq fdabqd qouxaB .pqfoqbege eU zaufmgomhq kmitsuT .kdqbbuxe kxszuiazw faz eu kmitsut qtF .femq szupmqT kxxmuoqbeq eqdufiaze qeg pzm egaufgmo kxqyqdfjq qN .eziaf zdqfemq edqtfaye zaufmfubuoqdb pqfoqbjqzG .iaze szuemqdozU :ftsuzaf dqtfmqi ftsuq eiqZ";
char *p = NULL;
char delimitor[] = " ";
char *target = "and";
int found = 0;
/* reverse the string */
reverse(code);
do
{
iteration++;
encode(code, iteration);
p = strtok(code, delimitor);
printf("%s\t%i\n", p, iteration); //test
/* while token isn't equal to NULL */
while( p != NULL )
{
/* compare token for instance of "and" */
if(strcmp(p, target)==0)
{
/* if found then break
out of loop */
found = 1;
break;
}
p = strtok( NULL , delimitor );
printf("%s\t%i\n", p, iteration);
if( ( p == NULL ) && ( iteration == 2 ) ) // PROBLEM
{
printf("\n\n%s\n\n", code);
}
}
if (found == 1)
break;
}
while(iteration < 25);
printf("Key Code is %i", iteration);
return 0;
}
void encode(char msg[], int key)
{
int i;
for ( i = 0; i < strlen(msg); i++ )
{
if ( islower(msg[i]) ) msg[i] = ( ( ( msg[i] - 97 ) + key ) % 26 ) + 97;
if ( isupper(msg[i]) ) msg[i] = ( ( ( msg[i] - 65 ) + key ) % 26 ) + 65;
}
}
void reverse(char msg[])
{
int c, i, j;
for ( i = 0, j = strlen(msg) - 1; i < j; i++, j-- )
{
c = msg[i];
msg[i] = msg[j];
msg[j] = c;
}
}