This is what I have so far. The issue is that the "count" variable is not properly adding to itself when it hits a newline or space character.
#include <stdio.h>
#include <stdlib.h>
int main(void){
char c;
int count = 0;
int* ptr;
int size;
FILE *file = fopen("file.txt", "r"); //Reads from input file
//Test to see if the file exists
if (file == NULL){
printf("ERROR 1: TARGET INPUT FILE DOES NOT EXIST, HAS BEEN RENAMED OR HAS BEEN MOVED.");
exit(1);
}
c = fgetc(file);
while ((c = fgetc(file)) != EOF){
if(c == " " || c == "\n"){
count++;
}
}
fclose(file);
printf("Number of words present in given file: %d", count);
return 0;
}
I don't have much of an idea as to why it is failing, although I have looked up multiple sources that have pretty much this exact code that seems to work for them. The output should return a number representing the amount of words in the .txt file.
For starters the variable
cshould be declared as having typeintinstead ofchar.Also ths call of
fgetcbefore the while loopis ignored
You are comparing an integer with pointers
because string literals in the above expressons are converted to pointers to their first characters. The compiler should issue a message for this if statement.
But if you will write instead
using character constants nevertheless the approach is incorrect because it does not take into account adjacent spaces.