我正在尝试学习c编程。
我写了这个小程序:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
// variable declarations
long nc;
char ch;
// initialize variables
nc = 0;
while ((ch = getchar()) != EOF) {
printf("%dt%cn", ch, ch);
++nc;
}
printf("Number of characters typed: %ldn", nc);
return EXIT_SUCCESS;
}
我创建了一个小文本文件,如下所示:
echo "abcdef" > text.txt
当我像这样运行这个程序时:
./countchar < text.txt
我得到以下输出:
97 a
98 b
99 c
100 d
101 e
102 f
10
Number of characters typed: 7
我的问题是在这种情况下 10 代表什么(换行?)以及为什么当我使用重定向运行此程序时它显示为第七个字符。
当你做echo "abcdef"
时,你会在最后得到一个换行符。这就是echo
默认的工作方式。因此,您的文本文件包含 7 个字符:abcdefn
.
您的 c 程序工作正常,并显示数字10
(ASCII 值为 n
)和文字换行符。
在大多数系统(但不是全部)上,您可以执行echo -n "abcdef"
以避免新行。或者(更便携),如果您关心换行符,请使用 printf
而不是 echo
。