Help with K & Rs key counting examples

I work through K & R 2nd edition, and I was puzzled by this seemingly simple example:

#include <stdio.h>

main(){
    double c;
    for(c = 0; ((getchar() != EOF) && (getchar() != '\n')); ++c)
        ;
    printf("%.0f\n",c);
}

It does not work properly. I added in the section (getchar() != '\n')to end the program when I press the enter button, but that also does not help.

Here is an example of the output using gccthat comes with the Mac OSX 10.6 dev tools.

pool-000:Desktop user$ ./a.out 
a
0
pool-000:Desktop user$ ./a.out 
asdf

2
pool-000:Desktop user$ ./a.out 
asfasf

3

So, something is clearly wrong. I am on page 18 if this helps. This is not homework, it is for fun!

Thanks:)

+3
source share
2 answers

Each call getchar()will wait for the character to read, so you read more than you think in an iteration of the loop.

, , , () double, , int.

+5

"getchar()" , TWO get chars ... ++ c.

"EOF", , .

+3

Source: https://habr.com/ru/post/1721638/


All Articles