Well what you need to do is break the input lines into words you can use say strcmp on.
Code:
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
int main()
{
char buff[BUFSIZ];
while ( fgets(buff,BUFSIZ,stdin) ) {
char token[BUFSIZ];
char *p = buff;
while ( *p != '\0' ) {
int pos;
if ( sscanf(p,"%[A-Za-z]%n",token,&pos) == 1 ) {
printf("Word=>>%s<< of length %d\n",token,pos);
p += pos;
}
if ( sscanf(p,"%[^A-Za-z]%n",token,&pos) == 1 ) {
printf("Non-Word=>>%s<< of length %d\n",token,pos);
p += pos;
}
}
}
return 0;
}
Example run:
$ ./a.out
int main()
Word=>>int<< of length 3
Non-Word=>> << of length 1
Word=>>main<< of length 4
Non-Word=>>()
<< of length 3
char buff[BUFSIZ];
Non-Word=>> << of length 2
Word=>>char<< of length 4
Non-Word=>> << of length 1
Word=>>buff<< of length 4
Non-Word=>>[<< of length 1
Word=>>BUFSIZ<< of length 6
Non-Word=>>];
<< of length 3
while ( fgets(buff,BUFSIZ,stdin) ) {
Non-Word=>> << of length 2
Word=>>while<< of length 5
Non-Word=>> ( << of length 3
Word=>>fgets<< of length 5
Non-Word=>>(<< of length 1
Word=>>buff<< of length 4
Non-Word=>>,<< of length 1
Word=>>BUFSIZ<< of length 6
Non-Word=>>,<< of length 1
Word=>>stdin<< of length 5
Non-Word=>>) ) {
<< of length 6
But you have to be careful, what answer would this code produce when you analyse it?
Code:
if ( strcmp(token,"if") == 0 )
printf("We found if\n"); // we found an if statement.
A simple interpretation would locate the word 'if' four times.