No Instance of Overloaded function while using STL queues - c++

Okay so I have a programming project due in about 7 minutes. My project reads a double GPA and a string Name in a txt file. I correctly place the GPA and Names into separate STL lists for the project. My problem comes when I try to push the highest GPA value into a queue. At that point it gives the error that no instance of overloaded function.
Since I am using pointers, I have tried different methods of using pointers but to no avail. I figure that pointers might be a part of the problem.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <list>
#include <queue>
using namespace std;
//using std::because it says cout is ambiguous even with std included
int main()
{
double GPA;
double highestGPA;
string name;
list<double> listGPA; //lists and their iterators
//list<double>::iterator ptrGPA, ptrHighestGPA;
double *ptrGPA, *ptrHighestGPA;
list<string> listName;
//list<string>::iterator ptrName, ptrHighestName;
string *ptrName, *ptrHighestName;
queue<double> queueGPA; //queues
//queueGPA.front() = 0;
queue<string> queueName;
//queueName.front() = "";
ifstream infile;
infile.open("HighestGPAData.txt");
if (!infile) //if file doenst exist
{
std::cout << "The input file does not "
<< "exist. Program terminates!"
<< endl;
std::system("pause");
return 1;
}
std::cout << fixed << showpoint;
std::cout << setprecision(2);
infile >> GPA >> name;
while (infile) { //place contents of file into 2 STL lists
listGPA.push_back(GPA);
listName.push_back(name);
infile >> GPA >> name;
}
std::cout << "\nSTL list for GPA:\n";
for (auto g : listGPA) { //range based for loop that prints GPA list
std::cout << g << "\n";
}
std::cout << "\nSTL list for names:\n";
for (auto s : listName) { //range based for loop that prints name
std::cout << s << "\n";
}
std::system("pause");
ptrGPA = &listGPA.front(); //initialize pointers for each list
ptrHighestGPA = ptrGPA;
ptrName = &listName.front();
ptrHighestName = ptrName;
while (!listGPA.empty()) // there are two lists (name and GPA)
if (ptrGPA > ptrHighestGPA) {
while (!queueGPA.empty()) { //destroy queue i (so a lower
queueGPA.pop();
}
while (!queueName.empty()) { //destroy queue if a higher //gpa is found (so a lower gpa is not printed)
queueName.pop();
}
/***********************problem here */
ptrHighestGPA = ptrGPA;
queueGPA.push(ptrHighestGPA); //add to queue if it is
ptrHighestName = ptrName;
queueName.push(ptrHighestName);
}
else if (ptrGPA == ptrHighestGPA) { //add to the queue ifcurrent gpa
queueGPA.push(ptrHighestGPA);
queueName.push(ptrHighestName);
}
/* end problem */
listGPA.pop_front();
listName.pop_front();
ptrGPA++;
ptrName++; //= listName.front();
}
while (!queueGPA.empty()) { //print the largest gpa.
std::cout << queueGPA.front() << " ";
queueGPA.pop();
}
std::cout << "\n";
while (!queueName.empty()) { //print who has the highest gpa
std::cout << queueName.front() << " ";
queueName.pop();
}
std::system("pause");
return 0;
}
Currently it outputs both lists but I can easily comment that out. I want the queues queueName and queueGPA to contain the highest GPA and name associated with that GPA from the lists listGPA and listName.
Thank you guys

Related

Vector of strings works correctly before sorting, but afterwards it can't do anything

I was working on a problem which required me to sort vector of strings at certain point. It caused me a lot of problems so I decided to extract the problematic part and I can't figure out what seems to be the problem.
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
bool myComp(string a, string b){
return a<b;
}
int main(){
vector<string> students(50000);
int i = 0;
while(true){
string input;
getline(cin, students[i]);
if(!students[i].empty()){
i++;
}
else{
break;
}
}
cout << students[2] << endl << students[1] << endl;
sort(students.begin(), students.end());
cout << students[2] << endl << students[1];
return 0;
}
At first I thought that input was wrong (problem specifically requests to read until empty line), but it turned out that program works correctly up to moment of sorting. I would be very grateful if anyone was to clear this out for me I am banging my head for more than an hour.
The obvious issue with your code is that you have a vector of 50000 strings. You then try an sort that vector of 50000 strings. It seems obvious that you really want the size of the vector to equal the number of strings input. The easy way to do that is to grow the vector as you input strings. Use the push_back method for that.
Here's some code
vector<string> students; // initial size of vector is zero
int i = 0;
while(true){
string input;
getline(cin, input); // read into the input variable
if (input.empty()) // break if input is empty
break;
students.push_back(input); // add the input to the vector
}
Now with the vector sized correctly you should find sorting it to be no problem
cout << students[2] << endl << students[1] << endl;
sort(students.begin(), students.end());
cout << students[2] << endl << students[1];
The problem is using incorrect arguments in the call of std::sort.
sort(students.begin(), students.end());
The vector students contains 50000 elements
vector<string> students(50000);
It seems you mean
#include <iterator>
//...
sort(students.begin(), std::next( students.begin(), i ));
or
sort(students.begin(), std::next( students.begin(), i ), myComp );
where myComp should be defined at least like
bool myComp( const string &a, const string &b){
return a<b;
}
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> students;
students.reserve(50000); // want to avoid `students` reallocation for first
// 50'000 entries but size is still zero (`0`)
std::string line;
// read until end-of-input or empty line
while(std::getline(std::cin, line) && !line.empty())
students.push_back(line); // no reallocation for first 50'000 entries!
if(students.size() < 3)
{
std::cerr << "Need at least three students for example\n";
return EXIT_FAILURE;
}
std::cout << students[2] << '\n' << students[1] << '\n';
std::partial_sort( // Only pick out three "smallest" strings for example
students.begin(), // no need to sort more than necessary with 50'000 :-)
std::next(students.begin(), 3),
students.end());
std::cout << students[2] << '\n' << students[1] << std::endl;
return EXIT_SUCCESS;
}
You have written a comparator function myComp() but you haven't used it. I'd suggest using it as the third parameter for sort() and see if things get better. i.e.;
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
bool myComp(string a, string b){
return a<b;
}
int main(){
vector<string> students(50000);
int i = 0;
while(true){
string input;
getline(cin, students[i]);
if(!students[i].empty()){
i++;
}
else{
break;
}
}
cout << students[2] << endl << students[1] << endl;
sort(students.begin(), students.end(), myComp);
cout << students[2] << endl << students[1];
return 0;
}

How to use selection sort on string vector of objects

I pretty new to coding and a lot of things are pretty foreign to me. I am writing a c++ program that is supposed to take a list of songs from a txt file and be able to shuffle, sort, and search for a song in the list. I have only started on the sorting part as of now, but I am having trouble finding out how to format the algorithm to work with my vector of songs.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstdlib>
#include <time.h>
#include <stdlib.h>
#include <bits/stdc++.h>
#include <algorithm>
#include "song.h"
using namespace std;
// given to you
void processFile(vector<Song> &playlist);
// you should create
void shuffle(vector<Song> &playlist);
void bubbleSort(vector<Song> &playlist);
void displayPlaylist(vector<Song> playlist);
int binarySearch(vector<Song> &playlist, string songTitle);
int main()
{
vector<Song> playlist;
// sets up playlist
processFile(playlist);
cout << "\nInitial playlist: " << endl;
//displayPlaylist(playlist);
displayPlaylist(playlist);
cout << "Welcome to the playlist display manager." << endl << endl;
while(1)
{
int option;
cout << "0. Exit" << endl;
cout << "1. Sort Playlist" << endl;
cout << "2. Shuffle Playlist" << endl;
cout << "3. Search Playlist" << endl;
cout << "Which option would you like" << endl;
cin >> option;
if(option == 0)
{
break;
}
else if(option == 1)
{
bubbleSort(playlist);
displayPlaylist(playlist);
}
else if(option == 2)
{
}
else if(option == 3)
{
}
else
{
cout << "invalid response...try again" << endl;
}
}
return 0;
}
void processFile(vector<Song> &playlist)
{
ifstream infile;
string line;
infile.open("songs.txt");
if(infile.is_open())
{
cout << "Successful songs opening." << endl;
}
else
{
cout << "Couldn't locate file. Program closing." << endl;
exit(EXIT_FAILURE);
}
while(getline(infile, line))
{
// first line --> song
// second line --> artist
if(line != "")
{
string song, artist;
song = line;
getline(infile, artist);
Song temp(song, artist);
playlist.push_back(temp);
}
}
return;
}
void shuffle(vector<Song> &playlist)
{
}
void selectionSort(vector<Song> &playlist, int n)
{
}
void bubbleSort(vector<Song>& playlist)
{
int size;
size = playlist.size();
for(int i= 0; i < size - 1; i++)
{
int smallIndex = i;
for(int j = i + 1; j < size; j++)
{
if(&playlist[j] < &playlist[smallIndex])
{
smallIndex = j;
}
}
string song, artist;
Song temp(song, artist);
temp = playlist[i];
playlist[i] = playlist[smallIndex];
playlist[smallIndex] = temp;
}
}
//display songs
void displayPlaylist(vector<Song> playlist)
{
for(int i = 0; i < playlist.size(); i++)
{
cout << playlist[i].getTitle() << " - " << playlist[i].getArtist() << endl;
}
}
Here is what I have so far. I am supposed to use a function to sort the sort the songs. The vector uses a class that was given to me to help classify the line of songs in the txt file by song then artist (title being the first thing listed in the line) and I'm supposed to sort by the title. This is just the last algorithm I attempted. I'm not required to use selection sorting. Whenever I call the function and try to display the list, it comes out the same.
edit: Sorry, it just occurred that I should probably go ahead and show all my code even if it's not done.
Your sorting algorithm is almost correct with small mistake .
You need to drop the & in if condition of your nested loop , you inner loop should be as follows ,
for(int j = i + 1; j < size; j++)
{
if(playlist[j] < playlist[smallIndex])
{
smallIndex = j;
}
}
Though this being said , since playlist is vector of Song objects , and you are using < operator on these objects , you will need to overload less-than < operator for your class . On the other hand , if you need to sort by song name or artist name , and they are well defined C++ objects(since most C++ library objects have already defined less-than operator for them) . For instance if song name or artist name are strings , and you need to sort by , let's say song name , then you can do it like this ,
if(playlist[j].song_name < playlist[smallIndex].song_name)
Here , you don't need to prefix the variable by ampersand & , you might be getting confused due to using ampersand with the variable playlist in function parameter list . Well , ampersand there is to tell the compiler to pass the variable as reference . For more information regarding reference variables , read the following links ,
What is reference variable in C++ and Reference variables

How to save unknown size structure (for later retrieval)

My plan is to store a couple dozen rows with 2 items per row and both items will have a different data type. Not sure if this is the right approach and have heard about using vectors but I can't find any samples that will take in 2 items with different types with many rows (an unknown amount of rows) similar to what I'm trying to do here. The following doesn't compile
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
struct movies_t {
string title;
int year;
} myRecNo[];
void printmovie (movies_t movie);
int main ()
{
string mystr;
for (int i=0; i < 2; i++)
{
switch (i)
{
case 1:
myRecNo[i].title = "2001 A Space Odyssey";
myRecNo[i].year = 1968;
cout << "Auto entry is:\n ";
printmovie (myRecNo[i]);
break;
case 2:
myRecNo[i].title = "2002 A Space Odyssey";
myRecNo[i].year = 1978;
cout << "Auto entry is:\n ";
printmovie (myRecNo[i]);
break;
}
}
return 0;
}
void printmovie (movies_t movie)
{
cout << movie.title;
cout << " (" << movie.year << ")\n";
}
This is the error I get:
Test1.obj||error LNK2019: unresolved external symbol "struct movies_t * myRecNo" (?myRecNo##3PAUmovies_t##A) referenced in function _main|
There are a couple of bad practices in your code, if you are just asking for a way to modify the program so that it will compile and work, see the following:
Declare struct and create struct variables in your main function.
struct movies_t
{
string title;
int year;
};
then, in your main function, movies_t myRecNo[2];
Arrays start at index 0, not 1. so your switch should be
switch (i)
{
case 0:
myRecNo[i].title = "2001 A Space Odyssey";
myRecNo[i].year = 1968;
cout << "Auto entry is:\n ";
printmovie(myRecNo[i]);
break;
case 1:
myRecNo[i].title = "2002 A Space Odyssey";
myRecNo[i].year = 1978;
cout << "Auto entry is:\n ";
printmovie(myRecNo[i]);
break;
}
// the rest of the code..
After you modify these, your code should work.
However, for a better data structure to save an array of paired values, you can use std::vector<std::pair<string, int>> myReg to save your data.
the following code should be much much better, remember to #include <vector>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
void printmovie(std::vector<std::pair<std::string, int>>);
int main()
{
std::vector<std::pair<std::string, int>> myReg;
myReg.push_back({ "2001 A Space Odyssey", 1968 });
myReg.push_back({ "2002 A Space Odyssey", 1978 }); // <- if your compiler is not using c++11 standard or above, please change this line to myReg.push_back(std::pair<std::string, int>("name of the movie", int)); to use to older version of Initializer
printmovie(myReg);
return 0;
}
void printmovie(std::vector<std::pair<std::string, int>> movie)
{
for (auto itor = movie.begin(); itor != movie.end(); ++itor)
{
//first is the first data in the pair, which is the title
//second is the second data in the pair, which is the year
std::cout << (*itor).first << " (" << (*itor).second << ")\n";
}
}
Thanks everyone & #Zhou.
Zhou's code above might work on a newer version of the compiler but I'm using Code::Blocks IDE with MS Visual C++ 2010 compiler.
Here is the vector method that worked:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
void printmovie(std::vector<std::pair<std::string, int>>);
int main()
{
std::vector<std::pair<std::string, int>> myReg;
myReg.push_back(std::pair<std::string, int>("title of the movie", 1968));
myReg.push_back(std::pair<std::string, int>("title of the movie2", 1978));
//myReg.push_back({ "2001 A Space Odyssey", 1968 });
//myReg.push_back({ "2002 A Space Odyssey", 1978 });
printmovie(myReg);
//or to print a single element (the 2nd row) thanks #zhou
std::cout << myReg[1].first << " " << myReg[1].second << std::endl;
return 0;
}
void printmovie(std::vector<std::pair<std::string, int>> movie)
{
for (auto itor = movie.begin(); itor != movie.end(); ++itor)
{
//first is the first data in the pair, which is the title
//second is the second data in the pair, which is the year
std::cout << (*itor).first << " (" << (*itor).second << ")\n";
}
}

Parsing set of Json files one by one

I am trying to parse Json files using JsonCpp library. but I am facing a problem Which I can not fix it. the code shown below is working perfectly when I am parsing one file but when I added the part which iterates over files in directory the program crashes.
The first function is used to search in a certain directory for Json files and save their names in vector of string (results).
In main function, the program starts by defining the extension required (.json) then calling search function. after that I tried to open each file to parse it.
Finally, Thanks and I really appreciate any kind of help.
#include "jsoncpp.cpp"
#include <stdio.h>
#include "json.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <dirent.h>
#include <vector>
using namespace std;
vector<string> results; // holds search results
// recursive search algorithm
void search(string curr_directory, string extension){
DIR* dir_point = opendir(curr_directory.c_str());
dirent* entry = readdir(dir_point);
while (entry){ // if !entry then end of directory
if (entry->d_type == DT_DIR){ // if entry is a directory
string fname = entry->d_name;
if (fname != "." && fname != "..")
search(entry->d_name, extension); // search through it
}
else if (entry->d_type == DT_REG){ // if entry is a regular file
string fname = entry->d_name; // filename
// if filename's last characters are extension
if (fname.find(extension, (fname.length() - extension.length())) != string::npos)
results.push_back(fname); // add filename to results vector
}
entry = readdir(dir_point);
}
return;
}
//
//
//
//
int main(int argc, char *argv[])
{
// read Files list
string extension; // type of file to search for
extension = "json";
// setup search parameters
string curr_directory = "/Users/ITSGC_Ready2Go/3dMap";
search(curr_directory, extension);
// loop over files
//if (results.size()){
//std::cout << results.size() << " files were found:" << std::endl;
for (unsigned int z = 0; z < results.size(); ++z){ // used unsigned to appease compiler warnings
// Opening the file using ifstream function from fstream library
cout <<results[z].c_str()<<endl;
Json::Value obj;
Json::Reader reader;
ifstream test(results[z].c_str());
//test.open (results[z].c_str(), std::fstream::in );
// Selection objects inside the file
reader.parse(test,obj);
//test >> obj;
// Parsing ID object and returning its value as integer
// cout << "id :" << stoi(obj["id"].asString()) <<endl;
// Parsing Line object with its internal objects
const Json::Value& lines = obj["lines"];
for (int i=0; i<lines.size();i++){
cout << "index : " << i << endl;
cout << "id:" << lines[i]["id"].asString() <<endl;
cout << "type:" << lines[i]["type"].asString() <<endl;
cout << "function:" << lines[i]["function"].asString() <<endl;
cout << "color:" << lines[i]["color"].asString() <<endl;
const Json::Value& poly = lines[i]["polyPoints"];
for (int j=0; j<poly.size();j++){
cout << "batch#"<<j<<endl;
cout << "latitude" << poly[j]["latitude"].asFloat()<<endl;
cout << "longitude" << poly[j]["longitude"].asFloat()<<endl;
cout << "altitude" << poly[j]["altitude"].asFloat()<<endl;
}
}
// Reading the OccupancyGrid object
// OccupancyGrid object is copied into constant to parse the arrays inside
const Json::Value& occupancyGrid = obj["occupancyGrid"];
cout << occupancyGrid.size() <<endl;
// The size of occupancyGrid is the used as number of iterations (#of rows)
for (int l=0; l<occupancyGrid.size();l++){
// Arrays inside occupancyGrid are copied into constant to parse the elements inside each array
const Json::Value& element = occupancyGrid[l];
// iterations over the size of the array in order to parse every element
cout << "row" << l << "--> ";
for (int k=0;k<element.size();k++){
cout << element[k].asFloat();
if(k<element.size()-1){ cout<< ",";}
}
cout << endl;
}
// Parsing roadSigns object as found in the file
// Need to understand the difference between format in the mail and the 1456 file
const Json::Value& roadsigns = obj["roadSigns"];
cout << "ArrayType: " << roadsigns["_ArrayType_"].asString()<<endl;
const Json::Value& ArraySize = roadsigns["_ArraySize_"];
for(int t=0;t<ArraySize.size();t++){
cout << ArraySize[t].asInt();
if (t<ArraySize.size()-1){ cout << " , ";}
}
cout<< endl;
if (roadsigns["_ArrayData_"].asString().empty()) {
cout << "ArrayData: "<<roadsigns["_ArrayData_"].asFloat(); }
else { cout << "ArrayData: empty "; }
cout <<endl;
test.close();
test.clear();
cout << "Done" << endl;
cout << "...." << endl;
cout << "...." << endl;
}
//else{
// std::cout << "No files ending in '" << extension << "' were found." << std::endl;
//}
}
Without access to the JSON library I can't help you too much, but the first obvious place for potential crashes would be if (fname.find(extension, (fname.length() - extension.length())) != string::npos). You need to make sure that your file name is longer than the size of your extension before making that call.
Also, for extremely deep directory trees you should put a limit on recursion, and all OSes I know of have some sort of character limit on directory and file names.

Storing a objects derived from an abstract base class with maps in a vector array of base class pointers

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 <=