下面的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/