繁体   English   中英

为什么即使满足退出条件,我的C程序也不会跳出while循环

[英]Why does my C program do not jump out the while loop even when the exit condition is met

#include<stdio.h>
#include <limits.h>

int main()
{
    int value;
    int smallest = INT_MAX;

    printf("This is a program that finds out the minimum \nof serveral integers you entered.");
    printf("Please type in these integers: ");

    while(scanf("%d", &value) != EOF)
    {
        printf(" ");

        if(value <= smallest)
        {
            smallest = value;
            printf("%d", smallest);    // to trace the while loop
        }
    }
    printf("\nThe smallest integer is: %d", smallest);    // this will execute once the program is stopped
    return 0;
}

这段代码可以成功找到最小的整数,但是不会打印出

printf("\nThe smallest integer is: %d", smallest);

..直到我从C语言解释器停止该程序。 我不明白为什么它不立即打印,因为while循环中没有更多的迭代。

更好的端环条件是

while (scanf("%d", &value) == 1)

这意味着scanf()正在成功读取值。

阅读链接以了解为什么,当使用scanf()时,等待EOF是不自然的,因为那样的话,用户将不得不按下一个组合键以将stdin标记为EOF

该键组合实际上非常笨拙,以至于Linux终端Ctrl + D和Windows cmd Windows Ctrl + Z都不相同。

如果它不执行printf()语句,那是因为您需要刷新stdout ,或者在每行的末尾添加fflush(stdout)或添加一个'\\n' ,在末尾添加换行更为自然,尽管我看到很多人在开始时就添加了它。

您不能使用像这样的EOF,因为scanf()在成功读取后会返回值1。 scanf()不会返回它读取的字符。 我在下面给出了解决方案,我认为它可以按照您的要求工作。对于下面的任何查询评论。

#include<stdio.h>
#include <limits.h>

int main()
{
    int value;
    int smallest = INT_MAX;

    printf("This is a program that finds out the minimum \nof serveral integers you entered.");
    printf("Please type in these integers (Enter any other character to terminate): ");
    while(scanf("%d", &value))
    {


        if(value <= smallest)
        {
            smallest = value;
            printf("smallest till now: %d\n", smallest);    // to trace the while loop
        }
        else
            printf("smallest till now: %d\n", smallest);    // to trace the while loop

     }  
     printf("\nThe smallest integer is: %d\n", smallest);    // this will execute once the program is stopped
     return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM