As soon as you've got some code working, refactor it to make functions out of it.
Code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX 100
int contains_word(const char *buff, const char *find)
{
char mask[MAX];
char delim[] = "\n.!?, ";
strcpy(mask, buff);
char* word = strtok(mask, delim);
int ok = 0;
while(word != NULL)
{
if(strcmp(word, find) == 0)
{
ok = 1; // if a word on the line coincides with the given word, stop comparing words => ok=1
break;
}
word = strtok(NULL, delim);
}
return ok;
}
int main()
{
char s[MAX];
char wordString[] = "ana";
unsigned lineCounter = 0;
unsigned ok;
while(fgets(s, sizeof s, stdin))
{
lineCounter++;
if( contains_word(s, wordString) )
{
printf("%d %s\n",lineCounter, s);
}
else
{
printf("The line doesn't contain the given word.\n");
}
}
}
Each function has a single well-defined purpose.
> I just want to know how can I print the line starting from the word I want.
> ... but I think I'm missing an idea).
At the point where you do ok = 1, you can do this.
Code:
position = word - mask;
Later on, you can do this.
Code:
printf("%d %s", lineCounter, &s[position] );