C中的字符数

Character Count in C

下面的C程序是计算字符数。

#include <stdio.h >
int main()
{
   int nc = 0;
   while (getchar() != EOF)
   {
      ++nc;
      printf("%d\n", nc); 
   }
    return 0;
}

当我在终端输入一个字符,比如'y',输出returns如下

1
2

这个计算是如何发生的,为什么输出中是 2?

您输入了 "a character"。一个 y 和一个换行符。那是 2.

当你按下回车键时,它被认为是一个字符

因为你输入了两个字符。一个是 y,另一个是 \n(换行)字符。

因此你得到输出 1 和 2。

我想你不知道,但当你按下回车键时,你只是插入了一个换行符或 '\n'。如果您想获得正确的结果,请忽略换行符或将 nc 减一。

#include <stdio.h>

int main()
{
  int nc = 0;
  while (getchar() != EOF)
  {
    ++nc;
    printf("Character count is:%d\n", nc - 1);
  }
  return 0;
}

更好的代码:

#include <stdio.h>
int main()
{
  int nc = 0;
  for(;;)
  {
    do
      ++nc;
    while (getchar() != '\n');
    printf("Character count is:%d\n", nc - 1);
    nc = 0;
  }
}

更新后的代码会将您的计数器重置为 0。

如果只想计算可见字节数,可以使用isprint函数,它returns一个字节是可打印的还是space字符。它是这样的:

#include <ctype.h>
#include <stdio.h>

int main()
{
  int nc = 0;
  int ch;

  while((ch = getchar()) != EOF)
  {
    if (isprint(ch) && ch != ' ')
      ++nc;
    printf("Character count after reading '%c' is %d.\n",ch, nc);
  }
  return 0;
}

请注意,由于在 C 中,char 不是 Unicode 字符,而通常只是一个字节,因此该程序将某些字符计为 2 个或更多字节,例如表情符号、西里尔字母、中文表意文字。