0

i have to count words of 3 files. The results should be 138, 166, 148 but they are 138, 165, 147. Can someone explain/help?

int countwords(const char* filename) {
    char z;
    int inw = 0;
    int words = 0;
    FILE *ed;
    ed = fopen(filename, "r");
    while ((z = fgetc(ed)) != EOF ){
        if (z == ' ' || z == '\n' || z == '\t' || z == '\0') {
            if(inw) {
                inw = 0;
                words++;
            }
        } else {
            inw = 1;
        }
    }
    fclose(ed);
    return words;
}``` 
destroy_mo
  • 14
  • 3
  • _Side note:_ Change `char z;` into `int z;` Otherwise, the loop might mistake a genuine 0xFF data value as EOF because the EOF (0xFFFFFFFF) would be compared identically to 0xFF due to the truncation to a `char`. `fgetc` returns an `int` for this reason. – Craig Estey Jun 19 '22 at 20:06
  • Your code has more than one problem. If words are followed by more than one spacing it will count an inexistent word. Anyway the problem you're asking about should probably be due to the missing space after the last word of file. In this case you'll find an `EOF` while `inw` is true. To solve check on exit if `inw` is true in which case increment word count. But it will be much better if you reconsider the whole logic. P.S. As Craig said `z` must be an `int`. – Frankie_C Jun 19 '22 at 20:09
  • You can find a better solution [here](https://stackoverflow.com/questions/12698836/counting-words-in-a-string-c-programming). You'll need to add some modifications to handle a whole file, not a string, which will be quite easy. – tshiono Jun 19 '22 at 23:36

0 Answers0