'"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.
Solution 1:[1]
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
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Inrin |
Solution 2 | Laurel |