使用 while 循环计算输入中的字符

counting characters in the input with while loop

我写了一个简单的 c 程序来计算字符数

#include <stdio.h>
main()
{
    long nc;
    nc = 0;

    while (getchar() != EOF)
      ++nc;

    printf("%ld\n", nc);
}

这个程序没有打印字符。在测试不同的情况时,我发现我陷入了无限的 while() 循环。

This program isn't printing me the characters

不会。您没有向 print 添加任何语句。

I found that i'm stuck in an infinite while loop

如果您不达到 打破 条件,您就会陷入困境。您需要获取 EOF 才能退出循环。使用

  • CTRL+Z(在windows上)
  • CTRL+D(在linux上)

现在,解决方案:

  1. getchar() 不会打印这些值。您必须使用 putchar().

  2. 存储这些值并显式打印(如果您愿意)
  3. 您要么提供 EOF,要么更改 while() 的中断条件,否则会跳出 essential 无限循环。


除了编码问题,你还需要考虑逻辑。在目前的代码形式中,getchar() 也将 newline (\n) 算作 valid 字符。解释一下,

形式的输入

$ ./a.out  ENTER
a      ENTER
s      ENTER
d      ENTER
f       ENTER
g      ENTER
CTRL+D

会产生一个结果

10

但那是不是我们通常所说的算字。您可能也想复习这部分逻辑。

也就是说,main()的推荐签名是int main(void)

尝试以下方法

#include <stdio.h>

int main( void )
{
    int c;
    long nc = 0;

    while ( ( c = getchar() ) != EOF && c != '\n' ) ++nc;

    printf( "%ld\n", nc );
}

您必须生成 EOF 状态(UNIX 系统中的 Ctrl+d 或 Windows 中的 CTRL+z)或直接按 Enter。

这样试试:

#include <stdio.h>

int main(void)
{
    int c;
    long nc = 0;

    while ( ( c = getchar() ) != EOF && c != '\n' ) 
    ++nc;

    printf( "%ld\n", nc );
}
while (getchar() != '\n')
   ++nc;
printf("%ld \n",nc);

成功了!