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
|
#include <iostream>
#include <fstream>
using namespace std;
#define MAX 10
void getGrades(int grades[], int num)
{
for (int i = 0; i < num; i++)
{
cout << "Grade " << endl;
cin >> grades[i];
}
}
int averageGrades(int grades[], int num)
{
int sumOfGrades = 0;
int average;
for (int i = 0; i < MAX; i++)
{
if (grades[i] == -1)
{
num--;
continue;
}
sumOfGrades += grades[i];
}
if (num == 0)
{
return false;
}
else
{
average = sumOfGrades / num;
return average;
}
}
int readFile(int grades[], int num, const char fileName[])
{
//Declare and open the output stream
ifstream fin("fileName.txt");
if (fin.fail())
return false;
//Read the data
int data;
fin >> data;
if (fin.fail())
return false;
//Close the stream
fin.close();
return data;
}
bool writeFile(int grades[], int num, const char fileName[])
{
//Declare the output stream
ofstream fout;
//Open the file
fout.open("fileName.txt");
if (fout.fail())
return false;
//Write the text
fout << grades[num];
if (fout.fail())
{
fout.close();
return false;
}
////Close the stream
fout.close();
return true;
}
int main()
{
//get source filename
char fileName[256];
cout << "Source file: ";
cin >> fileName;
int grades[MAX];
getGrades(grades, MAX);
readFile(grades, 10, fileName);
if (!readFile(grades, 10, fileName))
{
cout << "File " << fileName << " was unavailable for writing\n";
}
int average = averageGrades(grades, MAX);
if (average == false)
{
cout << "Average Grade: ---%" << endl;
}
else
{
cout << "Average Grade: " << average << "%" << endl;
}
cout << "Destination File: ";
cin >> fileName;
writeFile(grades, 10, fileName);
cout << "File written succesfully" << endl;
return 0;
}
|