在linux ubuntu 14.04中,我试图计算输入行:
#include <stdio.h>
/*count lines in input*/
main()
{
int c, nl;
nl = 0;
while ((c = getchar()) != EOF) {
if (c == '\n')
nl = nl + 1;
printf("input lines are %d\n", nl);
}
}
然而输出是:
asdsadsa
input lines are 0
input lines are 0
input lines are 0
input lines are 0
input lines are 0
input lines are 0
input lines are 0
input lines are 0
input lines are 1
asdasd
input lines are 1
input lines are 1
input lines are 1
input lines are 1
input lines are 1
input lines are 1
input lines are 2
答案 0 :(得分:1)
你缺少一些牙箍。
if (c == '\n') {
nl = nl + 1;
printf("input lines are %d\n", nl);
}
如果没有它们,那么只有nl增量会受到if语句的影响而你想要两者。
答案 1 :(得分:1)
没有你的期望,我只能猜到:
您可能需要这个(您必须使用Ctrl + D来表示输入结束):
#include <stdio.h>
/*count lines in input*/
int main()
{
int c, nl;
nl = 0;
while ((c = getchar()) != EOF) {
if (c == '\n')
nl = nl + 1;
}
printf("input lines are %d\n", nl);
}
或者这个(输入一行后立即打印):
#include <stdio.h>
/*count lines in input*/
int main()
{
int c, nl;
nl = 0;
while ((c = getchar()) != EOF) {
if (c == '\n')
{
nl = nl + 1;
printf("input lines are %d\n", nl);
}
}
}