I am trying to find the average of all the numbers of 2 files (numbers1.txt & more_numbers.txt). The average calculations are always incorrect. The smallest & largest numbers output correctly. Sorry if the codes messy, this is only month 3 of coding for me. Thank you.
#include <iostream>
#include <fstream>
#include <climits>
#include <string>
constint NFILES = 2 ;
const std::string file_names[NFILES] = { "numbers1.txt", "more_numbers.txt" } ;
int get_file_id() // return valid index into he array of file names
{
std::cout << "file list:\n-----------\n" ;
for( int i = 0 ; i < NFILES ; ++i ) std::cout << i << ". " << file_names[i] << '\n' ;
std::cout << "Which file would you like to open [0," << NFILES-1 << "]: " ;
int file_id ;
std::cin >> file_id ;
if( file_id >= 0 && file_id < NFILES ) return file_id ;
std::cout << "\nerror: invalid input. try again.\n" ;
return get_file_id() ;
}
void print_stats( std::istream& stm )
{
int smallest = INT_MAX ; // largest value that an int can hold
int largest = INT_MIN ; // smallest value that an int can hold
longlong sum = 0 ; // long long: sum of many int values may be outside the range of int
int cnt = 0 ;
int number ;
while( stm >> number ) // for each number read from the file
{
++cnt ;
if( number < smallest ) smallest = number ;
if( number > largest ) largest = number ;
sum += number ;
}
std::cout << cnt << " numbers were read\n" ;
if( cnt > 0 ) // if at least one number was read
{
std::cout << "smallest: " << smallest << '\n'
<< " largest: " << largest << '\n'
<< " average: " << double(sum) / cnt << '\n' ; // avoid integer division
}
}
void process_file( int file_id )
{
if( file_id < 0 && file_id >= NFILES ) return ; // invalid file_id
const std::string& fname = file_names[file_id] ;
if( std::ifstream file{fname} ) // if the file was opened for input
print_stats(file) ;
else std::cout << "error opening file " << fname << '\n' ;
}
int main()
{
constint file_id = get_file_id() ;
process_file(file_id) ;
}