在 Ritchie & Kernighan 着的 C Programming Language 一书中,在 §1.5.2 Counting Characters 中,给出了该程序的两个版本:
#include <stdio.h>
/* count characters in input; 1st version */
int main() {
long nc;
nc = 0;
while (getchar() != EOF)
{
++nc;
}
printf("%ld\n", nc);
}
和
#include <stdio.h>
/* count characters in input; 2nd version */
int main() {
double nc;
for (nc = 0; getchar() != EOF; ++nc) {
; // null statement
}
printf("%.0f\n", nc);
}
它们都能编译和工作,但总是输出比实际单词数多一个字符。
示例:
"milestone" (9 characters) outputs 10
"hello, world" (12 characters) outputs 13
这是为什么?
它是计算我在键盘上按 Return 给出的 '\0'
字符还是 '\n'
?
仅供引用:我在 MacOS 10.13.5 的终端上运行所有这些,文本已在 Atom 中输入。
最佳答案
它算“多一个”,因为 \n
也算在内。
例如:
echo -n "asdf" | ./a.out
输出:
4
但是换行:
echo "asdf" | ./a.out
输出
5
关于c - "C programming language"- 字符计数异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51583933/