I have a little problem related to the white spaces in my program. Well, the actual program I'm trying to make is something else. so this program is just to check whether the text is properly broken or not.
The problem I'm facing is, for the first word in my text, the node is made properly. but for the second word, if the string length is less than the first word, the compiler even considers the 'space'. I don't know why it is happening!! Can anyone help me out in this?
Here's the program:

#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
    char word[10];
    struct node* next;
}*HEAD=NULL,*TAIL=NULL;
void element(int,char *);
int main()
{
    char text[100],word[10]; int i=0,j;
    printf("Enter the text here: \n");
    gets(text);
    for(;text[i]!='\0';i++)
    {
        for(j=0;text[j]!=' ';j++,i++)
         {
            word[j]=text[i];
         }
        word[j]='\0';
        element(i,word);
    }
    getch();
     return 0;
}

void element(int x,char *y)
{
    int m=0;
    struct node *tmp;
    tmp=(struct node *)malloc(sizeof(struct node));
    while(m<=x)
     {
        tmp->word[m]=*(y+m);
        m++;
     }
    tmp->word[m]='\0';
    printf("%s ",tmp->word);
}

line 18: should be text[i] != ' '. You used the wrong loop counter.

After line 23 you should advance i counter until text[i] != space so that there can be more than one space between words

line 15: gets() is a bad function to use becuse it will allow you to type more characters then the buffer can hold, causing your program to crash. Instead of gets() use fgets() so that input length of limited to no more than buffer size. fgets(text, sizeof(text), stdin);

tmp->word[m]=*(y+m);

lines 34-38: Too compilicated. Just call strcpy() which doesn't need as loop. Unless of course if you are not allowed to use strcpy()

Edited 4 Years Ago by Ancient Dragon

This question has already been answered. Start a new discussion instead.