-1

I need just to count the number of chars in my 'f' file. When I count a number of chars in one string, I get the real number of it, but when I press 'enter' in my .txt and creating a new line I lose 2 chars. So, having 4 strings with 15 chars at all,my program telling me that there are only 9 chars in the file. Help me please to, just, count this unfortunate chars...
Here is a code in C:

while (!feof(f)) {
    bool space = 1; //remembering last char (was it space or not)
    for (int i = 0; i < len; ++i) { //running till the end of string
        if (a[i] == ' ') {space = 1;} 
        else if (a[i] != '\0' && a[i] != '\n') {
            chars++;
            if (space == 1) {
                words++; //and counting the words
                space = 0;
            }
        }
    }
}
SergeyA
  • 61,605
  • 5
  • 78
  • 137
Kouler
  • 3
  • 2

1 Answers1

1

In my opinion, the following would suffice:

int c; 
while ((c=fgetc(f))!=EOF) {
    if (c == ' ' || c=='\n') {
         words++;
    } 
    else {
        chars++;
    }
}
Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
  • 2
    `while (c=fgetc(f))` doesn't stop at EOF. Shouldn't it be `while ((c=fgetc(f))!=EOF)`? – Costantino Grana Mar 20 '19 at 14:57
  • and, of course, that doesn't mean, if you count space-chars, you have new words. You should see, if the last char was space and current is not. Then you will have the real number of words;) – Kouler Mar 23 '19 at 07:00