#include "assert.h"; // for some reason assert wouldn't work on my compiler without this
#include <iostream>
#include <string>
#include <limits> // This is helpful for inputting values. Otherwise, funny stuff happens
using namespace std;
class Product
{
public:
Product();
Product(string the_name, int the_price, int number_of);
string return_name();
void reduce_amount();
void print_data() const;
private:
string prod_name; // name of your product
int price_in_cents; // it's price in cents
int amount; // the number of the product that you have
};
Product::Product()
{
prod_name = "NULL_NAME: NEED DATA";
price_in_cents = 0;
}
Product::Product(string the_name, int the_price, int number_of)
{
assert(the_price>0);
assert(number_of>0);
assert(number_of<21);
assert(prod_name !="NULL_NAME: NEED DATA");
prod_name = the_name;
price_in_cents = the_price;
amount = number_of;
}
void Product::print_data() const
{
cout<<prod_name << endl;
cout<<"The price in cents is: " <<price_in_cents<< endl;
cout<< "Amount left: " << " " << amount << endl;
}
void Product::reduce_amount()
{
amount = amount -1;
}
string Product::return_name()
{
return prod_name;
}
class Vending_Machine
{
public:
Vending_Machine();
void empty_coins();
void print_vend_stats();
void add_product();
Product buy_product();
private:
int income_in_cents;
Product product1();
Product product2();
Product product3();
Product product4();
Product product5();
};
void Vending_Machine::empty_coins()
{
cout << "The total amount of money earned today is " << income_in_cents << " cents" << endl;
income_in_cents = 0;
cout << "All the coins have been withdrawn. The balance is now zero." << endl;
}
void Vending_Machine::print_vend_stats()
{
cout<< "Total income thus far: " << income_in_cents << endl;
if (product1().return_name() != "NULL_NAME: NEED DATA")
{
//stuff happens
}
}
int main()
{
return 0;
}
So, I'm not sure if I did all the identation correctly, but I'm having a problem with the boolean statement in vending machine print_vend_stats() function. It's saying I am making an undefined fereence to product1(). What does this mean?
When you declare
Product product1();
you declare a member function, the parentheses is what makes it a function.
If you drop the parentheses
Product product1;
you declare a member variable, an actual instance of the Product class.
Another example, you wouldn't write e.g.
int income_in_cents();
do declare income_in_cents as a variable, now would you?
It doesn't matter if the type is a primitive type like int, or a class like Product, Member variables are declared like normal variables like you do anywhere else.
Related
I am learning how to use classes in c++. Right now I'm working on a small program which should display the miles per gallon of a vehicle based on the given number of miles and gallons. The assignment says to call member functions within the main function in order to set the member variables within the Auto class. Here is my code:
#include <iostream>
using namespace std;
class Auto {
public:
string model;
int milesDriven;
double gallonsOfGas;
double calculateMilesPerGallon(int milesDriven, double gallonsOfGas) {
return milesDriven / gallonsOfGas;
}
void setModel(string newModel){
model = newModel;
}
void setMilesDriven(int newMiles){
milesDriven = newMiles;
}
void setGallonsOfGas(double newGallons){
gallonsOfGas = newGallons;
}
void output(){
cout << "A " << model << " was driven " << milesDriven << " miles, and used " << gallonsOfGas << endl;
cout << "This car gets " << calculateMilesPerGallon(milesDriven, gallonsOfGas) << "mpg.";
}
};
int main()
{
Auto modelFunction;
Auto milesFunction;
Auto gasFunction;
Auto outputFunction;
string carModel = "Toyota Camry";
int carMiles = 100;
double carGallons = 10;
modelFunction.setModel(carModel);
milesFunction.setMilesDriven(carMiles);
gasFunction.setGallonsOfGas(carGallons);
outputFunction.output();
return 0;
}
It's supposed to display something like "A Toyota Camry was driven 100, and used 10 gallons of gas, and gets 10 mpg." Instead, my output shows "A was driven -1538932792 miles, and used 4.66265e-310
This car gets -infmpg." What am I doing that is causing the output to be like this? I just started using classes so I don't have much experience with them. Thanks for the advice.
The error you're encountering is because you're creating four different Auto objects, each of which will have their own member variables. If you change your main function to the following, it will work:
int main()
{
Auto car;
string carModel = "Toyota Camry";
int carMiles = 100;
double carGallons = 10;
car.setModel(carModel);
car.setMilesDriven(carMiles);
car.setGallonsOfGas(carGallons);
car.output();
return 0;
}
Note that there is now only one 'Auto' object entitled 'car'.
You have to create only one instance of class Auto cause you only want to show the info for one car (with the name "Toyota Camry").
#include <iostream>
using namespace std; // strongly encouraging you to avoid using this
// in file scope
class Auto {
public:
string model;
int milesDriven;
double gallonsOfGas;
double calculateMilesPerGallon(/*no params required*/) {
return milesDriven / gallonsOfGas;
}
void setModel(string newModel){
model = newModel;
}
void setMilesDriven(int newMiles){
milesDriven = newMiles;
}
void setGallonsOfGas(double newGallons){
gallonsOfGas = newGallons;
}
void output(){
cout << "A " << model << " was driven " << milesDriven << " miles, and used " << gallonsOfGas << endl;
cout << "This car gets " << calculateMilesPerGallon() << "mpg.";
}
};
int main()
{
string carModel = "Toyota Camry";
int carMiles = 100;
double carGallons = 10;
Auto car;
car.setModel(carModel);
car.setMilesDriven(carMiles);
car.setGallonsOfGas(carGallons);
car.output();
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I don't know why but when i create an object with my class and use the default constructor, when i try to pass the variable named cash to the accessor user2.setCash(cash) which purpose is to primary set cash equal to new_cash, it gives a large value like 1.222256e+461 or something like that. Why does that happen? If i use my overload constructor it works fine.
main.cpp
#include <iostream>
#include <string>
#include "Bank.h"
using namespace std;
int main()
{
string name;
int id;
double cash;
bank user2;
cout << "\n\nPlease type your name: ";
getline(cin >> ws, name);
user2.setName(name);
cout << "Enter an id number: ";
cin >> id;
user2.setID(id);
cout << "Enter your cash: ";
cin >> cash;
cout << cash << endl;
user2.setCash(cash);
cout << "\nAlright " << user2.getName() << ", current cash: " << user2.getCash();
cout << "\nChoose how much would you like to Deposit: ";
cin >> cash;
user2.deposit(cash);
cout << "New amount is: " << user2.getCash() << " For user ID: " << user2.getID() << "\n\n";
bank::printStatic();
return 0;
}
Bank.h
#ifndef BANK_H
#define BANK_H
#include <iostream>
#include <string>
using namespace std;
class bank
{
public:
// Default Constructor
bank();
// Overload Constructor
bank(string, int, double);
// Destructor
~bank();
// Accessor Functions
string getName() const;
int getID() const;
double getCash() const;
// Mutator Functions
void setName(string);
void setID(int);
void setCash(double);
// Functions
void withdraw(double);
void deposit(double);
static void printStatic();
private:
// Member Variables
string new_name;
int new_id;
double new_cash;
// Static Member Variables
static int num_of_accounts;
static double total_cash;
};
#endif
Bank.cpp
#include "Bank.h"
// Static Variables
int bank::num_of_accounts = 0;
double bank::total_cash = 0.0;
// Default Constructor
bank::bank()
{
int new_id = 0;
double new_cash = 0.0;
++num_of_accounts; // New object is created e.g. a person so total accounts must be increased.
}
// Overload Constructor
bank::bank(string name, int id, double cash)
{
new_name = name;
new_id = id;
new_cash = cash;
++num_of_accounts; // New object is created e.g. a person so total accounts must be increased.
total_cash += new_cash; // New object is created e.g. a person so his/hers cash must be added to the total cash of the bank.
}
// Destructor
bank::~bank()
{
--num_of_accounts; // When Destructor is called to destroy an object (e.g. a person) then the id must be dropped by 1 cause the person e.g. (left).
total_cash -= new_cash; // And the balance he had to be removed so it is not counted in total cash avaliable in the bank cause he e.g. (left).
}
// Accessor Functions
string bank::getName() const
{
return new_name;
}
int bank::getID() const
{
return new_id;
}
double bank::getCash() const
{
return new_cash;
}
// Mutator Functions
void bank::setName(string name)
{
new_name = name;
}
void bank::setID(int id)
{
new_id = id;
}
void bank::setCash(double cash)
{
cout << new_cash << endl;
total_cash -= new_cash; // We must remove his prior cash which we holded in the total so we can then use the new value suplied.
new_cash = cash;
total_cash += new_cash; // Here we add the new cash (balance) he/she has.
}
void bank::withdraw(double cash)
{
new_cash -= cash;
total_cash -= cash;
}
void bank::deposit(double cash)
{
new_cash += cash;
total_cash += cash;
}
void bank::printStatic()
{
cout << "Total users are: " << num_of_accounts << endl;
cout << "Total cash in bank is: " << total_cash << endl;
}
You need to initialize all primitive type members in the constructor.
Otherwise you get indeterminate values
Also, the non-default constructor is buggy:
// Default Constructor
bank::bank()
{
int new_id = 0;
double new_cash = 0.0;
....
^ sets values of local variables, not the member variables
I'd suggest to use the initilization lists:
// Default Constructor
bank::bank() : new_name(), new_id(0), new_cash(0.0)
{
++num_of_accounts;
}
// Overload Constructor
bank::bank(string name, int id, double cash)
: new_name(name), new_id(id), new_cash(cash)
{
++num_of_accounts;
total_cash += new_cash;
}
You could also combine the two:
bank::bank(string name = "", int id = 0, double cash = 0.0)
: new_name(name), new_id(id), new_cash(cash)
{
++num_of_accounts;
total_cash += new_cash;
}
In your default constructor, you're declaring local variables with the same names as the member variables. Then you're setting these local variables instead of assigning the members. Get rid of the type declarations so they're normal assignments.
bank::bank()
{
new_id = 0;
new_cash = 0.0;
++num_of_accounts; // New object is created e.g. a person so total accounts must be increased.
}
I am new to this site (apologies if I am doing this wrong,) and fairly new to c++. I have run into an annoying error with an assignment for my c++ class
c++ error c2679: binary '[' : no operator found which takes a right-hand operand of type 'SalesItem' (or there is no acceptable conversion)
I'm not really sure what I need to include to help get an answer. I have included what I think to be the most relevant classes, leaving out the class with main(). I have not included the headers, but I should be able to add those in if needed...
Here is the Invoice class where I am finding this error, I have marked the lines where the error occurs with astriks(*):
#include "stdafx.h"
#include <iostream>
#include "Invoice.h"
#include <vector>
#include <string>
using namespace std;
static int nextInvoiceNum = 1000;
Invoice::Invoice(const string name, const int vectorSize)
{
customerName = name;
salesItems.reserve(vectorSize);
invoiceNumber = nextInvoiceNum++;
}
void Invoice::setCustomerName(string name)
{
customerName = name;
}
string Invoice::getCustomerName()
{
return customerName;
}
int Invoice::getInvoiceNumber()
{
return invoiceNumber;
}
void Invoice::display()
{
cout << "-------------------------\n";
cout << "\n Invoice #: " << getInvoiceNumber() << "\n";
cout << "\n Customer name: " << getCustomerName() << "\n";
cout << "-------------------------\n";
cout << "Items Purchased";
cout << "-------------------------\n";
for (auto &item : salesItems)
{
********cout << salesItems[item].display() << "\n";
cout << "-------------------------\n";
}
}
void Invoice::addSalesItem(SalesItem&)
{
salesItems.push_back(SalesItem());
}
double Invoice::getInvoiceAmount()
{
double runningTot = 0;
double total = 0;
for (auto &item : salesItems)
{
********runningTot = salesItems[item].getPartQuantity() * salesItems[item].getPartPrice();
total += runningTot;
}
return total;
}
Invoice::~Invoice(void)
{
}
What I am attempting to do is use a vector of objects and where the error first occurs is when I try to call the display() method from the SalesItems class using the vector.
Here is the SalesItem class:
#include "stdafx.h"
#include "SalesItem.h"
#include <iostream>
using namespace std;
SalesItem::SalesItem(string partNumber, string partDescription, int partQuantity, double partPrice)
{
partNumber = "";
partDescription = "";
partQuantity = 0;
partPrice = 0;
}
SalesItem::~SalesItem(void)
{
}
void SalesItem::setPartNumber(string number)
{
partNumber = number;
}
void SalesItem::setPartDescription(string description)
{
partDescription = description;
}
void SalesItem::setPartQuantity(int quantity)
{
partQuantity = quantity;
}
void SalesItem::setPartPrice(double price)
{
partPrice = price;
}
string SalesItem::getPartNumber()
{
return partNumber;
}
string SalesItem::getPartDescription()
{
return partDescription;
}
int SalesItem::getPartQuantity()
{
return partQuantity;
}
double SalesItem::getPartPrice()
{
return partPrice;
}
void SalesItem::display()
{
cout<< "-------------------------:";
cout<< "\n Part number: " << getPartNumber() << "\n";
cout<< "\n Part description: " << getPartDescription() << "\n";
cout<< "\n Part quantity: " << getPartQuantity() << "\n";
cout<< "\n Part price: $" << getPartPrice() << "\n";
cout<< "\n Invoice amount: $" << getInvoiceAmount() << "\n";
}
double SalesItem::operator+(double total)
{
double subtotal = getPartQuantity() * getPartPrice();
total += subtotal;
return total;
}
double SalesItem::getInvoiceAmount()
{
double invoice = getPartQuantity() * getPartPrice();
return invoice;
}
Again, sorry if I'm posting this in the wrong way. I would really appreciate some help with this. Will provide any other necessary info or make changes on a timely basis.
Thanks!
It's saying that the thing inside the square brackets is a salesItem object, but it was expecting an integer. The normal use of square brackets is to pick out one item out of a collection, using some kind of index, usually an integer. In this case, though, your for loop has already picked the item out, so you can just say "item.display()" instead of "salesItem[item].display()".
(You'd use salesItem[item].display() if instead your code looked sort of like this:)
int item;
for (item=0; item < ?however many sales items you have? ; item++) {
bla bla salesItem[item].display()
}
Your range for loop puts the reference to the item in item, not the index. Instead of salesItems[item] use item.
I'm having some problems with my program which I do not understand.
On line 72, I get the error: "error C4700: uninitialized local variable 'sumInEuros' used" however surely it is initialized as I am using it to store a calculation?
Also on line 66 I get "error C4716: 'showPriceInEuros': must return a value" - why must this return a value? the function is simply meant to output a message to the console.
I'm using VS13 and it's c++.
Any help would be very much appreciated, because I am stuck!
Thanks!
#include <iostream> //for cin >> and cout <<
#include <cassert> //for assert
#include <iomanip> //for endl
#include <Windows.h>
using namespace std;
void processAPrice();
int getPriceInPounds();
int convertPriceIntoEuros(int pounds);
int showPriceInEuros(int pounds, int euros);
int calculateSum(int euros);
void produceFinalData(int sum, int numberOfPrices);
int main()
{
char answer('Y');
int numberOfPrices(0);
while (answer = 'Y')
{
processAPrice();
numberOfPrices++;
cout << "Continue? (Y/N)";
cin >> answer;
}
if (numberOfPrices > 0)
//produceFinalData(sum, numberOfPrices);
system("PAUSE"); //hold the screen until a key is pressed
return(0);
}
void processAPrice() //
{
int pounds = getPriceInPounds();
int euros = convertPriceIntoEuros(pounds);
int sum = showPriceInEuros(pounds, euros);
calculateSum(euros);
}
int getPriceInPounds() //
{
int priceInPounds;
cout << "Enter a price (in Pounds): /234";
cin >> priceInPounds;
return priceInPounds;
}
int convertPriceIntoEuros(int priceInPounds) //
{
const int conversionRate(0.82);
return priceInPounds / conversionRate;
}
int showPriceInEuros(int pounds, int euros) //
{
SetConsoleOutputCP(1252);
cout << "The Euro value of /234" << pounds << "is: \u20AC" << euros;
}
int calculateSum(int euros) //
{
int sumInEuros;
sumInEuros = (sumInEuros + euros);
return sumInEuros;
}
void produceFinalData(int sum, int numberOfPrices) //
{
SetConsoleOutputCP(1252);
cout << "The total sum is: \u20AC" << sum;
cout << "The average is: \u20AC" << (sum/numberOfPrices);
}
Well, the showPriceInEuros function is not returning the int it promises to return in its signature. That's the error.
If the function is not supposed to return a value, you should declare its return type as void:
void showPriceInEuros(int pounds, int euros);
//^^
and then:
void showPriceInEuros(int pounds, int euros) {
SetConsoleOutputCP(1252);
cout << "The Euro value of /234" << pounds << "is: \u20AC" << euros;
}
of course.
surely it is initialized as I am using it to store a calculation?
The calculation is based on the variable's uninitialised value:
sumInEuros = (sumInEuros + euros);
^^^^^^^^^^ not initialised
Perhaps you could declare it static, so that its value is preserved between calls to the function, in order to calculate the sum of all the values you pass to the function. Usually, it would be better to use a class to manage persistent data like this, with member functions to update and access it.
why must this return a value?
Because you say it does:
int showPriceInEuros(int pounds, int euros)
^^^
If it shouldn't return a value, change the return type to void.
You do not initialize sumInEuros in this function. You store a result in it - that's true but to calculate the result you are using the uninitialized value.
int calculateSum(int euros) //
{
int sumInEuros;
sumInEuros = (sumInEuros + euros);
return sumInEuros;
}
Answering the question from below:
I would probably create a class PriceCalculator which has all the functions of your algorithm plus the internal state:
class PriceCalculator {
int m_sumInEuros;
public:
PriceCalculator()
: m_sumInEuros(0) { }
void processAPrice(int price);
int getSumInEuros() const { return m_sumInEuros; }
private:
void updateSum(int priceInEuros);
};
From your main function you should create an object of this type and give it the prices you want to sum. Do not do any console input from your class.
int main()
{
PriceCalculator calc;
char answer('Y');
int numberOfPrices(0);
while (answer = 'Y')
{
int priceInPounds;
cout << "Enter a price (in Pounds): /234";
cin >> priceInPounds;
calc.processAPrice(priceInPounds);
numberOfPrices++;
cout << "Continue? (Y/N)";
cin >> answer;
}
...
You might want to think about adding the numberOfPrices to your calculator class as well. At the end you will do all the operations in your class but the user input and console output outside your class. Your class can be tested automatically this way and is completely independent from the user interface.
I'm writing a program that uses OOP to store student records. At the moment I only have two classes, one for each individual course module called 'Courses', and one ( well two if you count the abstract base class) for the type of degree programme called 'Physics' derived from the 'Records' base class.
I'm using two maps in the program. One to store the individual courses for each individual record and sort them by course code, and one to store all the records and sort them by ID numbers.
I planned on having the user input all student information, including codes, storing this in a vector (named 'prec' in the code), then pushing the vector elements into the map used to store all the records. The code is far from finished, I was just attempting to run it to see if I was on the right track.
The code builds without any errors, but when I attempt to run it, it comes up with the error message: " Debug assertion failed: expression vector subscript out of range". I feel this may have something to do with the way I am using individual vector elements to call my functions to store courses in the maps but I cant quite get it, any help would be much appreciated!
Here are my files:
header file:
#ifndef MY_CLASS_H // Pre-processor directives to prevent multiple definition
#define MY_CLASS_h
#include <iostream>
#include <string>
#include <utility>
#include <map>
#include <fstream>
using std::string;
using std::ostream;
using std::map;
using std::cout;
using std::endl;
using std::cin;
namespace student_record // Defines the namespace student_record in which the classes are defined
{
class Course { /* Create class Course for individual courses, is this better than incorporating
all the data separately into the Record class below? Class contains course name, mark achieved and mark weight and course ID */
protected:
string course_name;
double course_mark;
int course_Id;
public:
Course() {course_name= "Null"; // Default constructor for null course
course_mark=0;
}
Course(string course_namein, double course_markin, int course_Idin) {course_name=course_namein; // Parametrized constructor to create course with set name, mark, weight and course ID
course_mark=course_markin;
course_Id=course_Idin;}
~Course() {course_name.erase(0,course_name.size());} // Destructor to delete the course name
// Access functions to get name, mark and weight //
double getmark() const {return course_mark;}
string getname() const {return course_name;}
int getid() const {return course_Id;}
friend ostream & operator << (ostream &os, const Course &c); // Friend function to overload the insertion operator for courses
};
class Record
{ // Create class Record as abstract base class for all inherited degree classes
protected:
string student_name;
int studentid;
int years;
public:
Record() {student_name="Casper";
studentid=0;
years=0;} // Default constructor for class Record, produces empty record
Record(string name, int number, int time) {student_name=name;
studentid=number;
years=time;} // Parametrized constructor for class Record
~Record() {student_name.erase(0, student_name.size());} // Destructor to delete the student name
virtual int getid()const=0;
virtual int getyears()const=0;
virtual void show_record()const=0;
virtual void print_record(string *filename)const=0;
virtual void degree_class()const=0;
virtual void insert_class()=0;
/* Virtual functions defined to be used in the derived classes (subjects ie, Physics, stamp collecting, etc...)
Thus the base class Record is abstract*/
};
class Physics: public Record
{
private:
string degree_name;
typedef map <int, Course> course_map;
course_map modules;
void searchdatabase (course_map &courses, int coursecode)const; // Uses iterator to search map for corresponding course to inputted key ( remember to move to function definitions)
string get_name (const int i, course_map &temp) const{ return temp[i].getname();}
double get_mark(const int i, course_map &temp)const{ return temp[i].getmark();} // Functions to return the mark, weight and name of a given course corresponding to inputed course code
int getid()const{return studentid;}
int getyears()const{return years;}
void show_record()const;
void print_record( string *filename) const;
void degree_class()const;
void insert_class();
// Function to insert record into map
public:
Physics():Record(){degree_name= "Physics ";}
Physics(string name,int Id, int time):Record( name, Id, time){degree_name= "Physics";}
~Physics() {degree_name.erase(0, degree_name.size());}
};
}
#endif
function definitions:
#include <iostream>
#include <string>
#include <utility>
#include <map>
#include <fstream>
#include <vector>
#include "Database_header.h"
using namespace std;
using namespace student_record;
ostream & student_record::operator<< (ostream &os, const Course &c)
{
os<< "Course code" << c.course_Id << " \n Course name: " <<c.course_name << " \n Mark " << c.course_mark <<endl;
return os;
}
// Function to insert classes //
void Physics::insert_class()
{
int courseid;
string coursename;
double mark;
cout << " Enter course code " << endl;
cin >> courseid;
cout << " \n Enter course name " << endl;
cin >> coursename;
cout << " \n Enter mark achieved " << endl;
cin >> mark;
Course temp (coursename, mark, courseid);
modules.insert(pair<int, Course>(courseid, temp));
}
void Physics::searchdatabase(course_map &courses, int coursecode) const // Function to search for specific course mark based on course code, need to modify this!!!!
//takes in a map as its argument, although i suppose can use student.modules?
{
course_map::iterator coursesIter;
coursesIter=courses.find(coursecode);
if(coursesIter != courses.end())
{
cout << " Course Code " <<
coursecode << " corresponds to " <<
coursesIter ->second << endl;
}
else { cout << " Sorry, course not found " << endl; }
}
void Physics::print_record( string *filename) const // Function for printing record to the file
{
ofstream myoutputfile;
myoutputfile.open(*filename,ios::app);
if(!myoutputfile.good())
{
// Print error message and exit
cerr<<"Error: file could not be opened"<<endl;
}
if(myoutputfile.good())
{
myoutputfile << "Student name: " << student_name << endl
<< "\n Student ID: " << studentid << endl
<< "\n Year: " << years << endl;
course_map::iterator modulesiter; // Iterator to print out courses using overloaded << function (I think?)
for(modulesiter==modules.begin();modulesiter!=modules.end();modulesiter++)
{
myoutputfile<<modulesiter->second << endl;
}
}
}
void Physics::show_record() const // Function for showing specific student record on screen ( with iterator for map of courses)
{
cout << "Student name: " << student_name;
cout << "\n Student ID: " << studentid;
cout << "\n Years on course: " << years;
cout << "\n Courses and grades: ";
course_map::iterator modulesiter; // Iterator to print out courses using overloaded << function (I think?)
for(modulesiter==modules.begin();modulesiter!=modules.end();modulesiter++)
{
cout<<modulesiter->second << endl;
}
}
void Physics::degree_class()const
{
double temp;
vector<double> dynarr; // Create a vector array to store the grades extracted from the course map for each student
course_map::iterator modulesiter;
for(modulesiter==modules.begin();modulesiter!=modules.end();modulesiter++) // Iterate through map and push values into each vector
{
Course ghost;
ghost=modulesiter->second;
dynarr.push_back(ghost.getmark());
}
double sum(0);
for(int i(0);i<=dynarr.size();i++)
{
sum+=dynarr[i];
}
temp=sum/dynarr.size();
if( temp>=40 && temp <=49.9)
{
cout << "The student has achieved a 3rd class degree with an average of: \n "
<< temp;
}
else if( temp>=50 && temp <=59.9)
{
cout << "The student has achieved a 2:2 degree with an average of: \n "
<< temp;
}
else if( temp>=60 && temp <=69.9)
{
cout << "The student has achieved a 2:1 degree with an average of: \n "
<< temp;
}
else if( temp>=70)
{
cout << "The student has achieved a 1st class degree with an average of: \n "
<< temp;
}
else { cout << "The student has failed the degree " << endl;}
}
and main cpp file:
#include <iostream>
#include <utility>
#include <map>
#include <iomanip>
#include <vector>
#include "Database_header.h"
#include <fstream>
using namespace std;
using namespace student_record;
void main()
{
// Create map to store students with ID keys //
string full_name;
int id;
int time;
string degree_name;
vector<Record*> prec;
// Vector of base class pointers to store all the different records first. No need to specify length as it is a vector! (Advantage over dynamic array?)
char student_test('y'); // Condition for adding students to the record //
int q(0);
while (student_test=='y' || student_test=='Y')
{
// Counter for while loop
cout<< " \n Please enter the student name " << endl;
getline(cin, full_name);
// Enter student name, check it is a string? //
cout<< "\n Please enter student ID " << endl;
cin >> id;
// Check if not integer or number, if not need error message //
cout << "\n Please enter the number of years on the course " << endl;
cin >> time;
// Check if not integer or number, if not need error message //
cout<< "\n Please enter degree type " << endl;
cin>>degree_name;
if(degree_name=="Physics" || degree_name=="physics") // create object of appropriate derived class ( Physics, Chem, Maths, Bio)
{
prec.push_back(new Physics(full_name, id, time));
}
char class_test('y'); // test condition for class insertion loop
while(class_test=='y') // Add courses+marks into course map
{
cout << " \n Add classes to student record " << endl;
prec[q]->insert_class();
cout << " \n Add another class? Y/N" << endl;
cin>>class_test;
}
cout << "Enter another student? Y/N " << endl;
cin >> student_test;
if(student_test=='N' && student_test=='n')
{
cout << "\n Thank you for using the student database, Goodbye !" << endl;
}
q++; // increment counter, to keep track of of vectors of base class pointers, and also be able to output number of students
}
// Next insert all records into map //
typedef map<int, Record*> studentlist;
studentlist studentmap;
for(int i(0); i<=prec.size(); i++)
{
studentmap.insert(pair<int, Record*> (prec[i]->getid(), prec[i]));
}
}
Thanks so much!
for(int i(0); i<=prec.size(); i++)
{
studentmap.insert(pair<int, Record*> (prec[i]->getid(), prec[i]));
}
Should be i < prec.size() instead of <=