所以我开始了C类,尽管我在C#和C ++方面有经验,但是我已经很早就坚持scanf = EOF
printf("Students, please enter heights!\n");
double maleAvg = 0, femaleAvg = 0;
int currentHeight = 0, malecount = 0, femalecount = 0;
while(scanf("%d",¤tHeight) != EOF)
{
if(currentHeight > 0)
{
femaleAvg += currentHeight;
femalecount++;
}
else if (currentHeight < 0)
{
maleAvg += currentHeight;
malecount++;
}
else
{
printf("Error! Invalid height 0!\n");
return 0;
}
}
if(femalecount == 0)
{
printf("No girls in class! :(\n");
}
else
{
femaleAvg /= femalecount;
printf("Average girls height is: %f\n",femaleAvg);
}
if(malecount == 0)
{
printf("No boys in class! :(\n");
}
else
{
maleAvg /= malecount;
printf("Average boy height is: %f\n",maleAvg);
}
return 0;
从我的理解中这是创建此循环的正确方法,因此它会一直读取到文件末尾。但是,我发现虽然它确实是根据写入的数字量进入循环的,但是在while循环之后却什么也没做,只是卡住了。我尝试在循环结束后立即打印一条消息,但没有打印任何内容。
答案 0 :(得分:1)
您的问题来自stdin
,它永远不会关闭,也永远不会在“正常”输入下返回EOF。您可以通过输入 Ctrl + D (在Linux上)和 Ctrl + Z (在Windows / DOS):
int main(int argc, char** argv)
{
int i;
int s = 0;
printf("Enter integer, Ctrl+D to compute the sum:\n");
while (scanf("%d", &i) != EOF) {
s += i;
}
printf("Sum = %d\n", s);
}
编译并运行:
Enter integer, Ctrl+D to compute the sum:
1
5
4
3
Sum = 13
但是您应该真正检查返回值并进行相应的处理,因为如果您输入例如1.2
(通常:总是检查返回值)。
请注意,正如@Toby Speight所指出的,您还可以从具有您喜欢的shell的文件重定向,该文件将发送EOF:
./a.out < numbers.txt
numbers.txt
如下:
1
5
4
3