帮助K&放大器;计数卢比为例字符数 [英] Help With K&Rs Counting Chars Example

查看:119
本文介绍了帮助K&放大器;计数卢比为例字符数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过K&放我的路; R的第二版,我一直在用难倒这个看似简单的例子:

I'm working my way through K&R's 2nd edition, and I've been stumped with this seemingly simple example:

#include <stdio.h>

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

这根本无法正常工作。我在(的getchar()!='\\ n')部分结束程序的时候我preSS进入,但也不至于的真的加的帮助的。

It simply isn't working correctly. I added in the (getchar() != '\n') portion to end the program when I press enter, but that doesn't really help either.

下面是一些示例输出,使用 GCC 附带的Mac OSX 10.6开发工具。

Here's some sample output, using the gcc that comes with 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

因此​​,一些显然是错误的。我是第18页,有没有什么帮助。这不是功课,这是乐趣!

So something is obviously wrong. I'm on page 18, if that helps. This isn't homework, this is for fun!

谢谢:)

推荐答案

每个调用的getchar()将等待一个字符被读取,所以你看比你想象的每循环的迭代。

Each call to getchar() will wait for a character to be read, so you're reading more than you think per iteration of the loop.

此外,至少在我看来,一个计数器(几乎)从来没有一个双击,你应该使用一个整数类型,如普通的老式 INT

Also, at least in my opinion, a counter is (almost) never a double, you should use an integer type such as plain old int.

这篇关于帮助K&放大器;计数卢比为例字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆