Hi! I am trying to figure out a way to store all tokens of a sentence into an array except the token 'done' which is the last word of the sentence, but not part of the sentence itself (it is purely there to signify the end of the sentence). After the tokens are stored into the WordList array, I need to print the contents of WordList.

Here's what I have so far:

#include <stdio.h>
#include <string.h>

struct WordStruct  // structure definition
{
	char Word[51];  // string that can store up to 50 characterss and the null string terminator
	int length;	// number of characters stored in the word (not including null)
} WordList[25];  // declare an array to store 25 words

int main()
{
	char InputString[] = "the cat in the hat jumped over the lazy fox done";
	// note that "done" is the last word in the sentence, but not part of sentence itself

	char *tokenPtr;  // create char pointer
	int i, j = 0;

	tokenPtr = strtok (InputString, " ");  // begin tokenizing sentence
	
	// continue tokenizing sentence until tokenPtr becomes NULL
	while (tokenPtr != NULL)
	{
		if (tokenPtr != "done")
		{
			WordList[i] = tokenPtr;  // tokens are stored
			tokenPtr = strtok (NULL, " "); // get next token
			i++;  // increase counter
		}
	}

	// print the contents of WordList
	for (j = 0; j < strlen (WordList); j++)
	{
		printf ("%c", WordList[j]);
	}
}

1. unless you want it for some other reason there is no need for the length member of the structure. You can easily get the word's length by calling strlen()

2. The program looked ok until the last loop where it is supposed to print each of the words. It should look something like this:

for( i = 0; WordList[i] != NULL && i < 25; i++)
{
   printf ("%s\n", WordList[i]);
}
int main ( void )
{
   static const char filename[] = "c:\\a.txt";  
   FILE *file = fopen ( filename, "r" );  
   if ( file != NULL ) 
   {    
     char line [ 128 ]; 
     while ( fgets ( line, sizeof line, file ) != NULL )   
	    {
	    	printf(" the new line is : %s",line);
	    	printf(" Starting tokenize: \n");
	    	char *token[20];
			int count = 0;
 			token[0] = strtok (line,",");
  			while (token[count] != NULL)
  			{
				count++;
				token[count] = strtok (NULL, ",");
			}
			for (int j = 0; j <= count -1 ; j++)	
			{	
				printf ("%s \n", token[j]);	
			}
			break;
  	    	printf("----------------------- Going for the next line------------------ \n");
		}
		
		fclose ( file );   
	}   
 return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.