1

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

Rui Yu
  • 113
  • 3
  • 11
  • 4
    Why the second `scanf()`? Shouldn't you just check the return from the first one? – Dmitri Feb 07 '17 at 04:37
  • 4
    As is, you scan `3.1415` into `f`, `7` into `i`, `.11` into `f`, `-15` into `i`, `.7` into `f`, then finish... and should get `"3 3 4\n0 0 1\n0 1 1\nDone.\n"` as output (your second `scanf()` eats the beginnings of most of the input numbers -- as much as can be interpreted as an integer). – Dmitri Feb 07 '17 at 04:50

2 Answers2

0

I think your second scanf is the problem, like others have already told you. How about doing it this way? The getchar() call seems to pick up the EOF more reliably.

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


int main (void) {
    float b;

    for (;;) {
        scanf("%f",&b);
        printf("%g %g %g\n",floor(b),round(b),ceil(b));
        if (getchar() == EOF)
            break;
    }

    return 0;
}
Micrified
  • 3,338
  • 4
  • 33
  • 59
0

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.

Community
  • 1
  • 1
izlin
  • 2,129
  • 24
  • 30