I'm writing program that counts words in C, I know I can do this simply with fscanf. But I'm using getc.
I have file like this:
One two three four five.
I'm reading chars in while loop and breaking point is when I reach terminal null.
Will c = fgetc(input);
or c = getc(input);
set c = '\0';
after One_ and after two_ etc.?
When a return value of a function like getc()
is EOF
which is -1,then you have reached the end of file.try this code to count words:
#include <stdio.h>
int WordCount(FILE *file);
int main(void)
{
FILE *file;
if(fopen_s(&file,"file.txt","r")) {
return 1;
}
int n = WordCount(file);
printf("number of words is %d\n", n);
fclose(file);
return 0;
}
int WordCount(FILE *file)
{
bool init = 0;
int count = 0, c;
while((c = getc(file)) != EOF)
{
if(c != ' ' && c != '\n' && c != '\t') {
init = 1;
}
else {
if(init) {
count++;
init = 0;
}
}
}
if(init)
return (count + 1);
else
return count;
}