-2

My program aims to print each word in the sentence on a separate line.but I should print it with %s not %c! I already try to implement it but the program does not give me a correct output ! my idea is when you find null character 1- print the word 2- return the index of the temp array to 0 and store a new word

 int main () {
    char sen[100];
    char cpy [100];
    printf("Entter a sentence "); 
    gets(sen);
    int len = strlen(sen);
    int i = 0; 
    int k =0;
    for (i=0 ; i<len;i++) 
    {
       if (sen[i]!='\0')
       {
          cpy[k++]+=sen[i];
       }
       else{
          printf("%s\n",cpy);
          k=0;}
    }

 }
Qix - MONICA WAS MISTREATED
  • 14,451
  • 16
  • 82
  • 145

3 Answers3

2

You confound null character and space character. Null character \0 stands for "end of string" : the strlen function returns the number of characters before the first \0.

In your forloop, you want to display each word separated by so you have to test with the caracter instead of \0.

Also to correctly display your string you have to end the string with the \0 character. So before the instruction printf you must do cpy[k] = '\0';.

Julien Vernay
  • 295
  • 3
  • 13
0

if (sen[i]!='\0') will always be true as pointed by Julien Vernay, you need if (sen[i]!= ' ') instead of if (sen[i]!='\0'), as there are spaces between words, to seprate them.

Also in cpy[k++]+=sen[i]; you are adding sen[i] to cpy[k++] which seams weird, I think what you need is cpy[k++] = sen[i];

Modify your loop as follows...

for (i=0 ; i<len; i++) {
   int flag = 0;
   while(sen[i] == ' ') i++; // multiple spaces

   while(sen[i] != ' ' && sen[i] != '\0') {
      cpy[k++] = sen[i];
      flag = 1;
      i++;
   }
   if(flag) {
     cpy[k] = '\0';
     printf("%s\n",cpy);
     k=0;
   }
}
Rajeev Singh
  • 3,292
  • 2
  • 19
  • 30
0

You can have to not bother with doing a copy - all you need to do is essentially replace spaces with new lines. So here is the code to do this:

#include <stdio.h>

int main()
{
   char sen[100];
   bool last_char_space = true;
   printf("Please enter a sentence: ");
   fflush(stdout);
   fgets(sen, 100, stdin);;
   for (int loop = 0; sen[loop]; ++loop) { // send[loop] is true until end of string - saves repeatedly calling strlen
     if (send[loop] == ' ') { // A space
       if (last_char_space) { // Last character not a space, put new line
         fputc('\n', stdout);
       }
       last_char_space = true; // Record the fact that we are between words
     } else {
       fputc(sen[loop], stdout); // Not a space - print it
       last_char_space = false;  // We are working on a word
     }
   }
   return 0;
}
Ed Heal
  • 59,252
  • 17
  • 87
  • 127