简体   繁体   English

在C语言中逐行读取带有strtol的文本文件

[英]Reading text files with strtol in C line by line

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 平均值应为:310422

Add an additional check in the if condition. if条件中添加其他检查。

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). 我利用以下事实:如果转换无效(如果字符串包含非数字字符), strtol返回0L But checking for this alone, also skips if the actual string contains 0 . 但是,仅检查这一点,如果实际字符串包含0 ,也会跳过。 I leave the rest to understand it yourself. 我让其余的人自己了解它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM