Exiting a while loop in EOF using scanf in C

I am writing some very small programs for my introductory course C. One of them requires me to read double values, one number per line, and then print the basic statistics after EOF. Here is my segment of my code that gives me problems:

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 that, I calculate and print statistics based on numbers.

My problem is that I never go out of a loop that scans every line. Why is this? When I press the EOF key on the windows (CTRL-Z?), The Console says:

^ Z Outboard

and that’s it. Nothing else in the program works. I tried to take input from a text file, but the end of the file was also not detected. How do I fix this loop? Note. I can use basic scanf () without changing a function. Thanks!

0
source share
2 answers

The code below simplifies your I / O problems.

" %lf " provides scanf () format 3 directives: 1) white space 2) double qualifier, 3) white space.

The first white space directive is not needed, as %lf allows optional leading spaces. The second white-space directive causes problems because it consumes the Enter key, waiting for additional input.

 "%lf" supplies 1 scanf() format directives: double specifier 

This consumes additional leading white space, including any previous \ n, then scans and, hopefully, decodes the double. A \n (Enter key), following the number, remains in the input buffer for the next input (next scanf ()).


Now about why your Z control is not working . It looks like your console is consuming ^ Z and doing "pause". My console, instead of passing ^ Z to the program, closes the stdin input. Essentially puts EOF in stdin.

So you need either:
1) Find a console mechanism to close stdin - others suggested ^ D.
2) Use an alternative to exit the loop. I suggest result != 1 , which easily occurs when entering non-numeric input.

 #include <stdio.h> int main(int argc, char *argv[]) { int result; double x = 0.0; do { // result = scanf(" %lf ", &x); /* Your original format */ result = scanf("%lf", &x); printf("%d %lf\n", result, x); fflush(stdout); // Your system may not need this flush } while (result != EOF); } 
+1
source

Ok guys, abandoning this first part of the project and debugging the other parts, I decided that my only problem with the above code is that I am trying to reference an array index that is out of bounds. I also determined that the EOF key is ctrl-d, although my professor said it was ctrl-z for windows. Despite this, it should be easy to fix. Many thanks to everyone who contributed!

0
source

Source: https://habr.com/ru/post/1490197/


All Articles