Question

OK so I've got this function which finds the average of all numbers in a file:

float averageOfNumbers(FILE *fp_in)
{
    int n=0,S=0;
    char red[1024];char *ptr;
    int p_a_h;
    float sr;

    while(!feof(fp_in)){
    if(fgets(red,1024,fp_in)!=NULL){
        ptr =red;
    while(p_a_h = strtol(ptr, &ptr, 10)){

        if((p_a_h>0&&S>INT_MAX-p_a_h)||(p_a_h<0&&S<INT_MIN-p_a_h)){
            printf("OVERFLOW\n");
            break;
        }
        else{
        S=p_a_h+S;
        n++;}

        }
    }
    }
    sr=S/n;
    return sr;
}

It works fine when there are only numbers in the file but if it finds anything other than a digit, the program will crash. How can I make it so that the program ignores other symbols. For example here is a text file:

wdadwa 321 1231 das 421124 1 wdasdad 4 1412515
sad14312 yitiyt453534 3554312 sad -2 -53 -12 -231 #@!
#!312 -2 241 -46343 sada 21312 65454

Average should be: 310422

Was it helpful?

Solution

Add an additional check in the if condition.

p_a_h==0 && (strlen(ptr)>1 || (strlen(ptr)==1 && ptr[0]!='0'))

I am making use of the fact that strtol returns 0L if the conversion is invalid(if the string contains non-digit characters). But checking for this alone, also skips if the actual string contains 0. I leave the rest to understand it yourself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top