I have written a program which opens a file of integers and computes max, min, average, total. I need to implement code which tests if there is any valid data in the file (i.e., if there are any lines in the file). I know I should use an if statement, but what condition would I put?
#include <iostream>
#include <fstream>
int main()
{
// if( std::ifstream file{ "numbers.txt" } ) // canonical
std::ifstream file( "numbers.txt" ) ;
int cnt = 0 ;
int number ;
while( file >> number ) // for each number in the file
{
++cnt ; // increment count
// add to total
// check for min, max
}
if( cnt > 0 ) // if at least one number was read
{
// caculate average
// print results
}
else
{
std::cerr << "error in reading numbers from file\n" ;
}
}