I am following "The C Programming Language. 2nd Edition", and have got up to "1.5.2 Character Counting".
The code provided for a character counter that uses a null statement is this:
#include <stdio.h>
main() {
double nc;
for(nc = 0; getchar() != EOF; ++nc)
;
printf("%.0f\n", nc);
}
Yet the program does not output the number of characters of the input:
input
input
Whereas if I included curly brackets and ignored the null statement:
#include <stdio.h>
main() {
double nc;
for (nc = 0; getchar() != EOF; ++nc) {
printf("%.0f\n", nc);
}
}
...it provides the correct output:
input
0
1
2
3
4
5
input
6
7
8
9
10
11
How do I make the null statement version of the program work?
You have plenty of issues in your code, but none of them is related to the empty statement:
main
type and arguments are wrongstdin
and function will not return EOF.Check for EOF and new line.
int main(void) {
int nc,ch;
for(nc = 0; (ch = getchar()) != EOF && ch != '\n'; ++nc)
;
printf("%d\n", nc);
}