user2805620
user2805620

Reputation: 125

How to do this assignment in C?

The following program prompts input to calculate the volume of a cylinder.How to terminate this program when any amount of non-numeric thing is entered?

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

float areaCirc(float r) {
    return (M_PI*r*r);
}

float volCyl(float r, float h) {
    return (areaCirc(r)*h);
}

int main(void) {
    float r, h;
    int k = 0;
    float volume;
    float avgh = 0;
    float toth = 0;

    do {
        scanf("%f%f",&r,&h);
        if(r<=0 || h<=0) {
            break;
        }
        volume = volCyl(r,h);
        k = k++;
        printf(" Cylinder %d radius %.2f height %.2f volume %.2f\n",k,r,h,volume);
        toth = toth + h;
    } while(r>0 && h>0);
    avgh = toth/k;
    printf("Total Height: %.2f\n",toth);
    printf("Average Height: %.2f\n",avgh);

    return EXIT_SUCCESS;
}

Upvotes: 0

Views: 114

Answers (2)

dinox0r
dinox0r

Reputation: 16059

From C++ Reference

On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file.

If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). And, if either happens before any data could be successfully read, EOF is returned.

If an encoding error happens interpreting wide characters, the function sets errno to EILSEQ.

Add the following modification to your code:

int res = scanf("%f%f",&r,&h);

if (res != 2) {
    printf("Expected two floating point numbers, aborting!\n");
    return EXIT_FAILURE;
}

That should abort the program if the user enters anything that is not a floating point number

Upvotes: 0

ryyker
ryyker

Reputation: 23236

scanf() returns the number of input items assigned, which can be fewer than provided for or zero in the event of an early matching failure. If an input failure occurs before any conversion, the function returns EOF (-1). If an error occurs, scanf sets errno to a nonzero value. So you can check the output of scanf, and determine if you should exit, or at least circle around for another try. This, I believe is what @Charlie means in his comment, and the reason @h3nr1x answer will work so well.

Upvotes: 1

Related Questions