Friends I am making a program to seach a string from a input line of strings.There are two problems :
(i)The program is giving correct search for word that is the 1st word of input line. e.g.,"hello" in hello friends how are you? but unsuccessful search for any word that is not the 1st word like "friends" or "how" in the above mentioned sentence.
(ii)I cannot input multiple lines starting from newline with gets or scanf as they stop reading when encounter new-line character.The input termination may be indicated by another special character like # instead of new-line.
The program I hope is self-explanatory .The logic is to use a pointer to word(*p) & input line buffer(*a) & match the character by character of the word in line input if not match the line input pointer(*a) is incremented till it reaches the 1st letter of next word,
/*program to take a line of input from user in
char buf[BUFSIZ] and to search for the
word entered in char word[5] in the previous input line*/
/*Run on Linux platform gives error that if the word to be
searched is successfully searched only if it is the
1st word of input line */
#include<stdio.h>
#include<string.h>
int main()
{
char word[5];i
char *a,*p,*b;
b=p=word;
//flag checks if a match has been found
int flag=0,len,count=0,disp=0;
char buf[BUFSIZ];
char *c;
a=buf;
printf ("Please enter a line of text, max %d characters\n", sizeof(buf));
if (fgets(buf, sizeof(buf), stdin) != NULL)
{
printf ("Thank you, you entered >%s<\n", buf);
/*
* Now test for, and remove that newline character
*/
if ((c= strchr(buf, '\n')) != NULL)
*c = '\0';
}
printf("\n\nEnter word needed\n");
printf("\n\nYou entered %s of length %d",word,len);
while(*a!='\0')
{
if(*a == *p)
{/*count shows how many continuous match of letters takes place*/
a++;p++;count++;printf("\nCount=%d",count);
}
else
{
if((count==len || count==len-1)
&&(*a ==' '|| *a == '\t' || *a == '\0'))
{
printf("\n\nMAtch");flag=1;
break;
}
else
{ if(*a == '\0')
{ break ;}
else
{
count=0;
while(*a != ' '|| *a != '\t' && *a != '\0' )
{ if(*a=='\0')
break;
else
{
/*disp is used to know how many times this loop works.*/
/*The Disp values printed shows that pointer(a)
is incremented to end while
no checking for matching is done*/
a++;disp++;
printf("\nDisp=%d",disp);
}
}
if(*a != '\0')
{ a++;p=b;}
}
}
}
if((*a == '\0') &&(count==len || count==len-1))
{ printf("\n\nMatch");
flag=1;
}
}
if(flag==0)
printf("\n\n\nNo Match");
return 0; --
}