C语言中的字符计数

C语言中的字符计数,c,getchar,C,Getchar,下面的C程序用于计算字符数 #include <stdio.h > int main() { int nc = 0; while (getchar() != EOF) { ++nc; printf("%d\n", nc); } return 0; } 这个计算是如何进行的,为什么输出中有2?您输入了“一个字符”。一个y和一个新行字符。这是2。当您按enter键时,它被视为一个字符,因为您输入了两个字符。一个是y,另一个是\n

下面的C程序用于计算字符数

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

这个计算是如何进行的,为什么输出中有2?

您输入了“一个字符”。一个
y
和一个新行字符。这是2。

当您按enter键时,它被视为一个字符

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


因此,您将得到输出1和2。

我想您不知道,但当您按enter键时,只需插入一个换行符或“\n”。如果要获得正确的结果,请忽略换行符或将nc减少1。

#include <stdio.h>

int main()
{
  int nc = 0;
  while (getchar() != EOF)
  {
    ++nc;
    printf("Character count is:%d\n", nc - 1);
  }
  return 0;
}
#包括
int main()
{
int nc=0;
while(getchar()!=EOF)
{
++数控;
printf(“字符计数为:%d\n”,nc-1);
}
返回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;
  }
}
#包括
int main()
{
int nc=0;
对于(;;)
{
做
++数控;
而(getchar()!='\n');
printf(“字符计数为:%d\n”,nc-1);
nc=0;
}
}

更新后的代码将计数器重置回0。

如果只想计算可见字节,可以使用
isprint
函数,该函数返回字节是可打印的还是空格字符。事情是这样的:

#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;
}
#包括
#包括
int main()
{
int nc=0;
int-ch;
而((ch=getchar())!=EOF)
{
如果(iPrint(ch)&&ch!='')
++数控;
printf(“读取“%c”后的字符计数为%d。\n”,ch,nc);
}
返回0;
}

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

尝试输入更长的字符串。我的猜测是,你总是会看到一个额外的字符(即,如果你输入ABCD,你将得到1 2 3 4 5)。因为你输入了两个字符-换行符也许我打赌你不只是按下
y
,而是在那之后按下了另一个字符。为什么
。。。nc=1?是的,你是对的,我用别的东西把代码弄乱了。谢谢!我会修好的。
++nc。更正语法问题。:)抱歉,正在从电话中写入:)第一个代码片段将只打印
0 1
,对
'\n'
没有特殊处理。第二个片段将运行一个无休止的循环,因为您从不测试
EOF
#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;
}