I am having trouble printing a sentence backwards the second time around through my loop without it printing the null values of the array. Is there anyway to get rid of the <NULL> that prints (for each word in the previous sentence) after each new sentence? Thanks. Here is my code:
Code:
#include <string.h>
#include <stdio.h>
void tokenThis();
int i;
int j = 0;
char *tokens[100];
char *tokenPtr;
char string[100];
int main ()
{
int choice;
printf("Enter 1 to exit or enter a sentence to be tokenized:\n");
scanf_s("%d",&choice);
while(choice!=1)
{
gets(string);//get the string
tokenThis();//call function to tokenize sentence
printf("\n\n\n");
memset(&tokens[0], 0, sizeof(tokens));
memset(&string[0], 0, sizeof(string));
printf("\nEnter a sentence to be tokenized or enter 1 to exit:\n");
scanf_s("%d",&choice);
}//end while
return 0;
}//end of main
void tokenThis()
{ // Get the first part
tokenPtr = strtok (string, " ");
// Get all following parts
//
while (tokenPtr)
{
// Store a word into array
tokens [j++] = tokenPtr;
// Pick next word (NULL token will stop the loop)
tokenPtr = strtok (NULL, " ");
}
// Print all parts in reverse order
printf ("\n\nThis is the sentence reversed:\n");
for (i = j - 1; i >= 0; i--)
{
printf ("%s ", tokens [i]);
}
}//end of tokenThis method