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))
  {


        //cout << "ssss";
        //continue;

        //}
    sum += f;
    count ++;
    cout  << fixed  <<  f << endl;


  }

  cout << setprecision(2) << fixed << count <<endl;
  cout << "average : " << sum/count << endl;

but it shows
12.100000
13.400000
12.400000
3
average : 12.63

Any suggestions

On line 1 when reading "12.4find" the first time it reads the line it reads the 12.4 and converts it to a float(? or double you don't say) and stores it in f.

The next time round the loop the next thing to read is "find", you request that this be converted to a float (or double) which can't be done. At this point the input stream enters an error state and (inputfile >> f) returns false and the loop stops.

If you want to read a file and handle errors then you would be better off reading each line as a std::string and then reading the value out of the string if you can

Open File

while(get_line_from_file)
{
   put line in stringstream
   read float from stringstream
   if (successful)
   {
     total += float
     count += 1
   }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.