Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to determine last words of each string?

Task

Enter a sequence of sentences from the keyboard into the string array (the end of entering – empty string) . Determine the last word of each of these sentences.

The problem is that my program outputs the last word of the last sentence, and I need the last word of each sentence to be output

Program i’ve tried

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

int main()
{
   char str[10][100];
   int i;

   printf("Enter a sequence of sentences:\n");

   for(i=0; i<10; i++)
   {
       if(*gets(str) == '\0')
          break;
   }

   printf("The last word of each of these sentences is:\n");

   for(i=0; i<10; i++)
   {
       char *word;
       word = strtok(str[i], ".");
       while (word != NULL) {
           char *last_word = word;
           word = strtok(NULL, ".");
       }
       printf("%s\n", last_word);
   }

   return 0;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The delimiter in this call

word = strtok(str[i], ".");

does not make sense.

It seems you mean

word = strtok(str[i], " \t.");

provided that a sentence can be ended only with a dot and words are separated by spaces or tab characters.

Another problem is that the variable last_word must be declared before the while loop.

For example

   char *last_word = NULL;
   char *word;
   word = strtok(str[i], " \t.");
   while (word != NULL) {
       last_word = word;
       word = strtok(NULL, " \t.");
   }

And it is better to use for loop instead of the while loop

   cjar *last_word = NULL;

   for ( char *word = strtok(str[i], " \t." );
         word != NULL;
         word = strtok(NULL, " \t.") ) 
   {
       last_word = word;
   }

Pay attention to that the function gets is unsafe and is not supported by the C Standard. Instead use standard C function fgets.

And the condition in the second for loop

for(i=0; i<10; i++)
{
    char *word;
    //...

is incorrect because the user can enter less than 10 sentences.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading