在 C 中使用 scanf 在 EOF 退出 while 循环 [英] Exiting a while loop at EOF using scanf in C

查看:18
本文介绍了在 C 中使用 scanf 在 EOF 退出 while 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的 C 入门课程编写一些非常小的程序.其中之一要求我读取双精度值,每行一个数字,然后在 EOF 后打印出基本统计信息.这是我的代码段给我带来的问题:

I'm writing a few very small programs for my introductory C course. One of them requires me to read in double values, one number per line, and then print out basic statistics after EOF. Here is my the segment of my code that is giving me issues:

double sample[1000000];
int result;
double number; 
int i = 0;
int count = 0;
double sum = 0;
double harmosum = 0;
result = scanf(" %lf 
", &number); 
double min = number;
double max = number; 

while(result != EOF){

    sample[i] = number;
    if(number < min){
        min = number;
    }
    if(number > max){
        max = number;
    }
    sum += number;
    if(number != 0){
        harmosum += (1 / number);
        count++;
    }
    i++;
    result = scanf(" %lf 
", &number);  
}

在此之后,我根据数字计算并打印一些统计数据.

After this I calculate and print some statistics based on the numbers.

我的问题是,我从来没有摆脱扫描每一行的循环.为什么是这样?当我在 Windows 上按下 EOF 键(CTRL-Z?)时,控制台说:

My issue is, I am never making it out of the loop that scans each line. Why is this? When I press the EOF key on windows (CTRL-Z?) the console says:

^Z暂停

就是这样.程序中没有其他任何内容运行.我曾尝试从文本文件中获取输入,但在那里也未检测到文件末尾.我应该如何修复这个循环?注意我只能使用基本的 scanf() 函数,没有变化.谢谢!

and that is it. Nothing else in the program runs. I have tried taking input from a text file but the end of the file is not detected there either. How should I fix this loop? Note I am only able to use basic scanf() no variation of the function. Thanks!

推荐答案

好吧,在放弃项目的第一部分并调试其他部分后,我确定我上面代码的唯一问题是我试图引用超出范围的数组索引.我还确定 EOF 键是 ctrl-d,尽管我已经阅读并被我的教授告知它是 windows 的 ctrl-z.无论如何,这应该很容易解决.非常感谢所有提供意见的人!

Okay guys, after giving up on this first part of the project and debugging the other parts, I have determined that my only issue with the code above is I am trying to reference an index of an array that is out of bounds. I have also determined that the EOF key is ctrl-d, even though I have read and been told by my professor that it is ctrl-z for windows. Regardless, this should be an easy fix. Thanks so much to everyone who provided input!

这篇关于在 C 中使用 scanf 在 EOF 退出 while 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆