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 \n", &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 \n", &number);
}
After this I calculate and print some statistics based on the numbers.
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 Suspended
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!
<ctrl> + <D>
combination that sendsEOF
? – user529758CTRL + Z
look here – Alexandru Barbarosie%lf
conversion skips initial whitespace, so the space before that does exactly nothing. The whitespace after the%lf
makesscanf
not return before it found the next non-whitespace character after the number has been scanned (or the end of input has been detected). You should probably checkwhile(scanf("%lf", &number) == 1)
, the return value is the number of successful conversions, andEOF
is only returned if a read error occurs, or the end of input/a matching failure occurs before the first successful conversion. – Daniel Fischer