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 144 145 146
|
int main()
{
get_array();
seeWhatsinthearray();//for testing only
sort(5);
seeWhatsinthearray2();
average(grades);
write_file();
system("pause");
return 0;
}
void get_array()
{
char filename[MAX_PATH + 1];
int n = 0;
char name[20];
int grade=0;
//int age = 0;
int recsize = sizeof(name) + sizeof(int);
//int recsize = sizeof(names) + sizeof(int);
cout << "Enter file name: ";
cin.getline(filename, MAX_PATH);
// Open file for binary read-write access.
fstream fbin(filename, ios::binary | ios::in | ios::out);
if (!fbin)
{
cout << "Could not open " << filename << endl;
cout<< "re-enter a valid file: ";
cin.getline(filename, MAX_PATH);
}
// Get record number and go to record.
cout<< "this is the information on file: " << endl;
cout<< left << setw(20)<< "name" << setw(4) << "grade" << endl;
int i=0;
while(! fbin.eof())
{
fbin.seekp(n * recsize);
// Read data from the file.
fbin.read(name, sizeof(name) - 1);
fbin.read((char*)(&grade), sizeof(int));
cout << endl << left<< setw(20)<< name << setw(4)<< grade << endl;
grades[i] = grade;
names[i] = name;
n++;
i++;
}
fbin.close();
}
void seeWhatsinthearray()
{
cout << "This is the information in my array: ";
for(int i=0; i<5; i++)
{
cout<< endl << left<< setw(20) << names[i] << setw(4) << grades[i] << endl;
}
}
void seeWhatsinthearray2()
{
cout << "This is the information in my array after being sorted: ";
for(int i=0; i<5; i++)
{
cout<< endl << left<< setw(20) << names[i] << setw(4) << grades[i] << endl;
}
}
int get_int(int default_value) {
char s[81];
cin.getline(s, 80);
if (strlen(s) == 0)
return default_value;
return atoi(s);
}
void sort(int x) {
int i,j, tempnumbers;
string tempn;
for (i=0; i<=length; i++)
{
for (j=i+1; j<length; j++)
{
if (grades[i] > grades[j])
{
tempnumbers = grades[j];
grades[j] = grades[i];
grades[i] = tempnumbers;
tempn = names[j];
names[j] = names[i];
names[i] = tempn;
}
}
}
}
void average(int grades[5])
{
int sum=0;
for (int i=0;i<=5;i++)
{
sum = sum + grades[i];
}
int avg= sum/5;
cout<< "this is the average: ";
cout<< avg <<endl;
}
void write_file()
{
char filename[MAX_PATH + 1];
int n = 0;
char name[20];
int grade=0;
int recsize = sizeof(name) + sizeof(int);
cout<< "enter the name of the file for destination: "<< endl;
cin.getline(filename,MAX_PATH);
fstream fbin (filename, ios::binary |ios::out);
for (int i=0;i<length;i++)
{
fbin.seekp(n * recsize);
grade= grades[i];
name = names[i].c_str();
fbin.write(name,sizeof(names[i])-1);
fbin.write((char*)(&grade),sizeof(int));
n++;
}
fbin.close();
}
|