C 中的字符数

标签 c getchar

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

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

当我在终端输入一个字符,例如'y'时,输出返回如下

1
2

这个计算是如何进行的以及为什么输出中出现 2?

最佳答案

我想您不知道,但是当您按 Enter 时,您只需插入一个换行符或 '\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。

关于C 中的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39189661/

相关文章:

c - getchar() != EOF

c - 使用gcc命令行从.c文件构建.so文件

c - 从 csv 读取,strtod 无法读取带有数字的字符串

c - char 指针 (strdup) 时使用 printf 的段错误

计算e的幂(e^x),为​​什么n=999?

c - 实现永远循环时遇到问题

c - 如何使用循环找到一对加起来也达到一定总和的除数?

c - 为什么 scanf 会跳过获取字符串输入?

c - while(scanf) : why does using getchar() keep the input going 输入问题

python - 在 Python 中获取单个字符作为输入,无需按 Enter(类似于 C++ 中的 getch)