Rui Yu Rui Yu - 1 year ago 86
C Question

Infinite loop in C

The program should accept input values on stdin until EOF is reached. The input is guaranteed to be well-formed and contain at least one valid floating point value.

Sample input:

3.1415
7.11
-15.7


Expected output:

3 3 4
7 7 8
-16 -16 -15
Done.


#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main(void)
{
for(;;)
{
float b;
scanf("%f", &b);
printf("%g %g %g\n",floor(b), round(b), ceil(b));
int i=0;
int result = scanf("%d", &i);

if( result == EOF)
{
printf("Done.\n");
exit(0);
}

}
return 0;
}


My program only runs one time. After that it outputs
0 1 1

Answer Source

If you want to stay with the scanf, you can use the return value to detect a erroneous/EOF input:

#include <stdio.h>  
#include <math.h>  
#include <stdlib.h>  

int main(void) 
{  
    int result = 0;
    for(;;)  
    {  
        float b;
        result = scanf(" %f", &b); 
        if(result == EOF)
            break;

        printf("%g %g %g\n",floor(b), round(b), ceil(b));  
     }  
     printf("Done");
    return 0;  
} 

Try it here.

Also a look at this question is helpful.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download