A
Amir S.
Hi,
I'm a newbie to C++ (2 weeks into the course). We were given this
assignment to write some code that reads a set of integers (grades)
from a file (filename passed by console), outputs them in reverse
order, calculates and prints their average.
=> We have been told that we need to make sure that our code meets
"information hiding" guidelines. Could anyone help me get started with
this (any ideas?)
Thank you for your help,
Dave
Here is my code (functionality-wise it's correct, it also compiles):
#include <iostream>
#include <fstream>
using namespace std;
int main (int argc, char* argv[]) {
int numItems = 0;
int counter;
double sum = 0;
if (argc <= 1 ) {
cerr << "Usage: ./q2 \"filename\"" << endl;
exit (1);
}
ifstream is_rawGrades (argv[1]);
if (is_rawGrades == NULL) {
cerr << "Couldn't open the file " << argv[1] << endl;
exit (1);
}
is_rawGrades >> numItems;
//case where there is only a 0 in the file
if (numItems == 0){
cout << "No items in the file."
<< "NaN";
}
//declare array and initialize counter
int items[numItems];
counter = 0;
//loops till finds number of items specified
while (true) {
int grade;
is_rawGrades >> grade;
if (is_rawGrades.fail()) {
break; // out of while loop
}
items[counter] = grade;
sum += grade;
counter++;
}
//outputs array contents in reverse
for (int i = numItems; i>0; i--){
cout << items[i-1] << ";";
}
//calculates and prints out average
double avg = sum / numItems;
cout << endl << avg << endl;
}
I'm a newbie to C++ (2 weeks into the course). We were given this
assignment to write some code that reads a set of integers (grades)
from a file (filename passed by console), outputs them in reverse
order, calculates and prints their average.
=> We have been told that we need to make sure that our code meets
"information hiding" guidelines. Could anyone help me get started with
this (any ideas?)
Thank you for your help,
Dave
Here is my code (functionality-wise it's correct, it also compiles):
#include <iostream>
#include <fstream>
using namespace std;
int main (int argc, char* argv[]) {
int numItems = 0;
int counter;
double sum = 0;
if (argc <= 1 ) {
cerr << "Usage: ./q2 \"filename\"" << endl;
exit (1);
}
ifstream is_rawGrades (argv[1]);
if (is_rawGrades == NULL) {
cerr << "Couldn't open the file " << argv[1] << endl;
exit (1);
}
is_rawGrades >> numItems;
//case where there is only a 0 in the file
if (numItems == 0){
cout << "No items in the file."
<< "NaN";
}
//declare array and initialize counter
int items[numItems];
counter = 0;
//loops till finds number of items specified
while (true) {
int grade;
is_rawGrades >> grade;
if (is_rawGrades.fail()) {
break; // out of while loop
}
items[counter] = grade;
sum += grade;
counter++;
}
//outputs array contents in reverse
for (int i = numItems; i>0; i--){
cout << items[i-1] << ";";
}
//calculates and prints out average
double avg = sum / numItems;
cout << endl << avg << endl;
}