I got a almost good working program to count words from standard input.
The word what has to be count is a program argument.
The problem is that I use a white space to see a word but I also must count within th word itself.
Example: if my input is aa aaaa #EOF, and I want to count aa the result should be 4. My code result 2.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
int word_cnt(const char *s, char *argv[])
{
int cnt = 0;
while(*s != '\0')
{
while(isspace(*s))
++s;
if(*s != '\0')
{
if(strncmp(s, argv[1], strlen(argv[1])) == 0)
++cnt;
while(!isspace(*s) && *s != '\0')
++s;
}
}
return cnt;
}
int main(int argc, char *argv[])
{
char buf[1026] = {'\0'};
char *p="#EOF\n";
int tellen = 0;
if (argc != 2)
{
printf("Kan het programma niet uitvoeren, er is geen programma argument gevonden\n");
exit(0);
}
while((strcmp(buf, p) !=0))
{
fgets (buf, 1025, stdin);
tellen += word_cnt(buf, argv);
}
printf("%d", tellen);
return 0;
}
1 Answer