-
help with EOF
hello, i am working on this program that calculates the resistance of an arbitrary number of floating points, the input needs to end when i press zero or EOF...i have the zero part but for some reason i can't get the EOF part....
here is my code
Code:
#include <stdio.h>
#define SENTINAL 0
int main()
{
double r1;
double resistance = 0.0;
printf("Enter the resistance or zero to end input:\n");
while ( 1 ) {
scanf("%lf", &r1);
if ((r1 == SENTINAL))
break;
resistance += (1/r1);
}
if (resistance == 0)
printf("\nNo values entered.\n\n");
else
printf("\nTotal resistance of the ciruit is %.3f ohms\n", 1/resistance);
system("pause");
return 0;
}
i have tried
Code:
if ((r1 == SENTINAL) || (r1 == EOF))
break;
i have also tried saying
Code:
if (scanf("%lf", &r1) == EOF)
break;
the scanf code ends the input but it changes my numbers...can anyone give me any insight to what i am doing wrong? thanks
-
rl can never have the value EOF. scanf will return the value EOF. Since you need to check for both EOF and zero, then do so:
Code:
if (retval == EOF || inputval == 0)
-
I think you should write your loop like this instead:
Code:
while (scanf("%lf", &r1) == 1 && r1 != SENTINAL) {
resistance += 1.0 / r1;
}
Incidentally, I think that SENTINAL should be SENTINEL, and you really should indent your code more consistently.
-