NotationMaster
NotationMaster

Reputation: 410

"C programming language" - Counting characters anomaly?

In The C Programming Language book by Ritchie & Kernighan, in §1.5.2 Counting Characters, two versions of the program are given:

#include <stdio.h>

/* count characters in input; 1st version */
int main() {
    long nc;
    nc = 0;

    while (getchar() != EOF)
    {
        ++nc;
    }

    printf("%ld\n", nc);
}

and

#include <stdio.h>

/* count characters in input; 2nd version */
int main() {
    double nc;

    for (nc = 0; getchar() != EOF; ++nc) {
        ; // null statement
    }

    printf("%.0f\n", nc); 
}

They both compile and work but always output one more character than the actual count of the words.

Example:

"milestone" (9 characters) outputs 10  
"hello, world" (12 characters) outputs 13

Why is this?
Is it counting the '\0' character or the '\n' given by me hitting the Return on the keyboard?

FYI: I am running all this on Terminal on MacOS 10.13.5 and the text has been inputted in Atom.

Upvotes: 0

Views: 566

Answers (2)

fazli
fazli

Reputation: 11

It counts your "enter" input too: your word +1 enter input = x+1 counts.

If you type the first value as "EOF value" which is cntrl+z for Windows, the loop won't count "enter" because it will reach "EOF value" before your "enter" input and the output will be zero.

Upvotes: 1

Inrin
Inrin

Reputation: 322

It counts "one more" because \n is counted as well.

For example:

echo -n "asdf" | ./a.out

Outputs:

4

But with a newline:

echo "asdf" | ./a.out

it outputs

5

Upvotes: 4

Related Questions