gpt4 book ai didi

c - 仅在 "if loop"内的 "while loop"中打印一次

转载 作者:行者123 更新时间:2023-11-30 18:51:45 27 4
gpt4 key购买 nike

在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

最佳答案

没有你的预料,我只能猜测:

您可能需要这样(您必须使用 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);
}
}
}

关于c - 仅在 "if loop"内的 "while loop"中打印一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36121371/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com