0

I am reading these values from a file
12.1
13.4
12.4find
gg
16.77
56.55
My program should display the average of 5 float no and ignore find and gg.
I did

 while((inputfile >> f))
  {

        istringstream iss(f);
        if(!(iss(f))
           {
           iss.clear();
           continue;
           }
    sum += f;
    count ++;
    cout  << fixed  <<  f << endl;

It is not giving the right result.

2
Contributors
1
Reply
12
Views
3 Years
Discussion Span
Last Post by tinstaafl
0

If you want accuracy you should use double instead of float.

A combination of reading the next character in the file and ignore will help you skip the unwanted parts:

double f,sum=0;
int count = 0;
while(!file_id.eof())
{
    char nextchar = file_id.peek();
    if(isdigit(nextchar) || nextchar == '.')
    {
        file_id >> f;               
        sum += f;
        count ++;
    }
    else 
        file_id.ignore(20,'\n');

    cout << f << '\t' << sum << '\t' << count << '\t' << sum/count << endl;
}

Edited by tinstaafl

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.