The statement is:
Write a program that prints all entities of the form &name; (where name is formed of letters) appearing in the input, separated by one space.
Code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX 100
int checkWord(char word[])
{
size_t len = strlen(word);
for(int i = 0; i < strlen(word); i++)
{
if(!isalpha(word[i]) || (word[0] != '&') || (word[len-1] != ';'))
{
return 0;
}
}
return 1;
}
int main()
{
char s[MAX];
while(fgets(s, MAX, stdin))
{
char* word = strtok(s, " ");
while(word != NULL)
{
// printf("%s\n", word);
printf("%d\n", checkWord(word));
if(checkWord(word) == 1)
{
printf("%s ", word);
}
word = strtok(NULL, " ");
//printf("%s", word);
}
}
return 0;
}
The program should work well but checkWord always returns 0 and never actually enters the if block. I don't understand what I'm missing, checkWord checks if the word is formed by letters only, starts with '&' and ends ';' but for the input:
john goes to &school; everyday
Output:
0
0
0
0 // this should be 1 and therefore &school; should be printed
0
What am I doing wrong?