1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
|
using namespace std;
ofstream outputfile("output.txt");
const int MAX_FILE_NAME = 35;
const int MAX_NUMBER_SCORES = 50;
void open_input(ifstream& input, char name[]);
void read_values(ifstream& input, double v[], int size, int& used);
void find_average(const double v[], int n, double& average);
void output(const char name[], double sarray[], int n, double average, ostream &out = cout);
int main()
{
char again;
char file_name[MAX_FILE_NAME + 1];
ifstream input_numbers;
double scores [MAX_NUMBER_SCORES];
double average;
int num_scores;
cout << " This program finds the average of numbers in a file and outputs ";
cout << " the average to a file" << endl;
cout << endl;
cout << endl;
system("pause");
do
{
cout << endl;
cout << endl;
cout << endl;
open_input(input_numbers, file_name);
read_values(input_numbers, scores, MAX_NUMBER_SCORES, num_scores);
input_numbers.close();
if (num_scores > 0)
{
find_average(scores, num_scores, average);
output(file_name, scores, num_scores, average);
output(file_name, scores, num_scores, average, outputfile);
}
else
{
cout << "\n\n No data in File: " << file_name << endl;
}
cout << "\nDo you want to process another file (Y/N)? ";
cin >> again;
cin.ignore(256, '\n');
}
while ( again == 'y' || again == 'Y');
cout << "\nThe End!" << endl;
outputfile.close();
return 0;
}
void open_input(ifstream& input, char name[])
{
int count = 0;
do
{
count++;
if (count != 1)
{
cout << "\n\aInvalid file name or file does not exist. Please try again."
<< endl;
}
cout << "\nEnter the input file name (maximum of " << MAX_FILE_NAME << " characters please)\n:> ";
cin.get(name, MAX_FILE_NAME + 1);
input.open(name, ios_base::in);
input.clear();
}
while (input.fail() );
}
void read_values (ifstream& input, double v[], int size, int& used)
{
double value;
int count = 0;
while (count < size && input >> value)
{
v[count] = value;
count ++;
}
used = count;
}
void find_average(const double v[], int n, double& average)
{
int i, sum = 0;
for (i = 0; i < n; i++) { sum = sum + v[i]; }
average = sum / n;
}
void output(const char name[], double sarray[], int n, double average, ostream& out)
{
out.setf(ios::fixed);
out.setf(ios::showpoint);
out.precision(2);
out << "\n\nInput File Name: " << name << endl;
out << "\nFile Contents:" << sarray << endl;
int sort = 0, index = 0;
for(int i = 0; i < n ; i++)
sort = i;
if ( n > 0 && sarray[n-1] > sarray[n] )
{
swap (sarray[n], sarray[n-1] );
n--;
}
out << "\nAverage of Numbers in File: " << setw(8) << average << endl;
}
|