我在使用k&r 1.5.3时遇到了麻烦.显然我是一个完全的初学者.下面是完全来自本书的代码,正如我输入的那样.它编译好并运行.它返回字符,但从不打印行数.我正在使用ssh进入Ubuntu机器.我妻子的Mac上的钥匙可以解释为'\n'吗?
#include <stdio.h>
/*count lines in input*/
main()
{
int c, n1;
n1 = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
++n1;
printf("%d\n", n1);
}
Run Code Online (Sandbox Code Playgroud)
正确.Mac \r用作行结尾:http://en.wikipedia.org/wiki/Newline
像这样更新您的代码:
#include <stdio.h>
/*count lines in input*/
main()
{
int c, n1;
n1 = 0;
while ((c = getchar()) != EOF)
if (c == '\r') /* use \r for Macs */
++n1;
printf("%d\n", n1);
}
Run Code Online (Sandbox Code Playgroud)
然而
当我尝试做同样的事情时,我必须Ctrl-D输入EOF并触发程序来打印行数.