1.5.2 character counting

Nothing is odd with the program here but if you don’t take care of two points here,you may get puzzled with the output display.

//1.5.2 character counting

#include <stdio.h>
main()
{
    long cn;
    cn = 0;
    while (getchar() != EOF){
        ++cn;
        }
    printf("%1d\n",cn);
    system("pause");
}

image 
I can’t get the result at first,for that time,I directly enter a string with an ENTER,but find nothing given,that is,it don’t seem to work properly but the code is properly written,what’s wrong?
Asking a friends,I get the result,there’s nothing wrong with the code,but something not properly with the output.Check with the DOS blank like this:
type in a string that you want to test,and then turn to a new line type in ctrl and z,at last you will get a properly displayed answer.

ctrl+Z在控制台中就是EOF,输入的字符串末尾没有EOF,所以while循环会无限执行下去,以致无法执行printf部分,所以在控制台中输入zrtl+Z,给定一个EOF使得输入的string有这个结束符,就能跳到下一个printf了

Leave a comment