0

好的,所以我有这个函数可以找到文件中所有数字的平均值:

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;
}

当文件中只有数字时它可以正常工作,但如果它找到除数字以外的任何内容,程序将崩溃。我怎样才能使程序忽略其他符号。例如这里是一个文本文件:

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

平均值应为:310422

4

1 回答 1

0

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.

于 2014-03-23T09:55:27.710 回答