开发者

Counting character code in C

Ok I'm just learning C and stumble upon this practice code to count character K&R's book:

#include <stdio.h>
/* count characters in input; 2nd version */
main()
{
    double nc;
    for (nc = 0; get开发者_如何学运维char() != EOF; ++nc)
        ;
    printf("%.0f\n", nc);
}

The problem is I don't know whether is it suppose to print the amount of characters or not when I entered any character because there is no output whatsoever, just whitespace (getchar() waiting for another input).

Can someone explain to me what is going on? I'm practicing in bash using vim in openSUSE 11.3.


You have to send the EOF signal/character to the program. If you are running it from inside a terminal window, press Ctrl+D.

If you are piping from a file, like so:

./my_program < input_file_name

then it will work automagically.


Since it is checking for EOF, hit Ctrl-D in the terminal.


As others have mentioned, you have to press control-d (aka ^d) but that only works after you hit return. In other words you cannot type "foocontrol-d" and expect it to work. "fooreturncontrol-d" would work, though.

Also please note that K&R is a fine fine book, but was written decades ago. The counting algorithm presented only work on ASCII-ish input. Wide characters (UTF-8, etc) would not be counted correctly.

Also also note, the example you quoted is using a floating point number for this counting. There is little strictly wrong with this, but for speed and efficiency, most people would use unsigned ints, longs, or some other intergral datatype. You are not likely to be reading ¾th of a character!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜