How to Define CountProbation() function using Functions from other Files? - c++

I have been racking my brain on how to properly define the function CountProbation() properly in the Course.css file. I know that a for and if loop should probably be included but I am having trouble including functions from other files, even though I am including a header tag at the beginning of the current Course.css file.
Below are the C++ files that are given in the lab:
NOTE: Only the Course.cpp file is the one that needs to be edited. All of the other files are READ ONLY and purely for your information as the reader.
Sorry if it seems like a lot of code, but I didn't just want to include the Course.cpp file because then you might not understand the program.
Here are the compiler Errors/Warnings:
Course.cpp: In member function ‘int Course::CountProbation()’:
Course.cpp:8:18: warning: comparison of integer expressions of different signedness: ‘int’ and ‘std::vector<Student>::size_type’ {aka ‘long unsigned int’} [-Wsign-compare]
8 | for (int i=0; i < roster.size(); ++i) {
| ~~^~~~~~~~~~~~~~~
Course.cpp:9:9: error: ‘GetGPA’ was not declared in this scope
9 | if (GetGPA() < 2.0) {
| ^~~~~~
Course.cpp
#include <iostream>
#include "Course.h"
#include "Student.h"
using namespace std;
int Course::CountProbation() { //This is the function that I have tried to define as you can see by my
int probCount; //code
for (int i=1; i < roster.size(); ++i) {
if (GetGPA() < 2.0) {
probCount = probCount + 1;
}
}
return probCount;
}
void Course::AddStudent(Student s) {
roster.push_back(s);
}
Course.h (READ ONLY)
#ifndef COURSE_H
#define COURSE_H
#include <vector>
#include "Student.h"
class Course {
public:
int CountProbation();
void AddStudent(Student s);
private:
vector<Student> roster; //collection of Student objects
};
#endif
Main.cpp (READ ONLY)
#include <iostream>
#include <string>
#include "Course.h"
using namespace std;
int main() {
Course course;
int probCount;
// Example students for testing
course.AddStudent(Student("Henry", "Cabot", 3.2));
course.AddStudent(Student("Brenda", "Stern", 1.1));
course.AddStudent(Student("Lynda", "Robison", 2.4));
course.AddStudent(Student("Jane", "Flynn", 1.8));
probCount = course.CountProbation();
cout << "Probation count: " << probCount << endl;
return 0;
}
Student.h (READ ONLY)
#ifndef STUDENT_H
#define STUDENT_H
#include <string>
using namespace std;
// Class representing a student
class Student {
public:
Student(string first, string last, double gpa);
double GetGPA() ;
string GetLast();
private:
string first; // first name
string last; // last name
double gpa; // grade point average
};
#endif
Student.cpp (READ ONLY)
#include "Student.h"
// Student class constructor
Student::Student(string first, string last, double gpa) {
this->first = first; // first name
this->last = last; // last name
this->gpa = gpa; // grade point average
}
double Student::GetGPA() {
return gpa;
}
string Student::GetLast() {
return last;
}

This loop (as it was coded in the original question, before it was edited):
for (int i=1; i < roster.size(); ++i) {
if (Student.GetGPA() < 2.0) {
probCount = probCount + 1;
}
}
is flawed for three reasons:
i should start from 0, rather than 1
i should be of type size_t, rather than int
Student is a type, not a variable
A nice way to solve all these problems is to use a ranged for loop, like this:
for (Student &student : roster)
{
if (student.GetGPA() < 2.0)
probCount = probCount + 1;
}
As mentioned in the comments, you also need to initialise probCount to zero before entering the loop:
int probCount = 0;
Finally, it's worth noting that the above loop would normally be coded as:
for (const Student &student : roster)
{
...
but that won't work here as GetGPA is not declared as a const method. Thanks to #user4581301 for pointing this out.

Related

Using member function to solve equation C++

I am currently trying to create a program to calculate the mass of a rocket with given time values by passing an array to a member function of a class. I get these two errors and can't seem to figure out how to get rid of them. Any suggestions are much appreciated, thank you.
23 8 [Error] prototype for 'double equip::calcmass(double)' does not match any in class 'equip'
13 10 [Error] candidate is: double equip::calcmass()
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstring>
using namespace std;
class equip
{
public:
double mass[999999999], velocity, height, time[999999999];
double calcmass();
private:
double T = 7000;
double g = 32.2;
double K = 0.008;
};
double equip::calcmass(double time)
{
int i = 0;
for(i=0; i=999999999; i++)
{
return mass[i] = (3000 - 40 * time[i]) / g;
}
}
int main()
{
int i = 0;
equip rocket;
ifstream infile;
string filename;
cout<<"Enter input file name for time (time): ";
cin>>filename;
infile.open(filename.c_str());
while(infile.fail())
{
cerr<<"Error opening file. \n";
cout<<"Enter file name: ";
cin>>filename;
infile.open(filename.c_str());
}
for(i=0; i<999999999; i++)
{
infile>>rocket.time[i];
}
for(i=0; i<999999999; i++)
{
cout<<rocket.mass[i];
}
return 0;
}
In your class definition you've declared
double calcmass()
In the definition of the member function it's
double calcmass(double time)
They do not match. One takes a double as argument and the other does not.
You were missing a bunch of headers, and in the function declaration was missing the parameter presents in the function definition:
#include <cmath>
#include <cstring>
#include <fstream>
#include<iostream>
using namespace std;
class equip
{
public:
...
double calcmass(double time); // here was missing the parameter
...
};
double equip::calcmass(double time)
{
...
}
Also you are doing time[i] on time which is a double, so you can't use operator[]... If you want to pass an array, you can use pointer to double:
class equip{
...
double calcmass(double* time)
}
double equip::calcmass(double* time)
{
...
}

sort array of objects alphabetically c++

I am enrolled in an Object Oriented programming class and am using code::blocks as my IDE. We have a project that requires to pass an array of objects ( a Libray book array with private names and titles) into a sort array that will sort the titles or authors alphabetically. I have all the components working as they should be except the sort function. I used a sort function that I have used before in other programs but am having trouble getting it to work with this program. I am still in the beginning stages of learning how to code and would appreciate any feedback.
Header file:
#include <iostream>
#include <cstring>
using namespace std;
class Book
{
private:
string title;
string author;
public:
Book();
string getTitle();
string getAuthor();
void setTitle(string Title1);
void setAuthor(string Author1);
};
Main:
#include <iostream>
#include <cstring>
#include <iomanip>
#include "Library.h"
using namespace std;
//Sort function prototype
void s_sort (Book lib_books[], int n);
int main()
{
// Initializes n as the number of books
int n = 15;
//Declaration of array of objects
Book lib_books[15];
// Declartion of the private member "title" for each object
lib_books[0].setTitle("The Alchemist");
lib_books[1].setTitle("The Princess Bride");
lib_books[2].setTitle("The Catcher in the Rye");
lib_books[3].setTitle("1984");
lib_books[4].setTitle("Fahrenheit 451");
lib_books[5].setTitle("The Great Gatsby");
lib_books[6].setTitle("Poland");
lib_books[7].setTitle("The Cantebury Tales");
lib_books[8].setTitle("Leaves of Grass");
lib_books[9].setTitle("Where the Sidewalk Ends");
lib_books[10].setTitle("The Iliad");
lib_books[11].setTitle("Things to Think On");
lib_books[12].setTitle("The Grapes of Wraith");
lib_books[13].setTitle("Hop on Pop");
lib_books[14].setTitle("The Prince and the Pauper");
// Declartion of the private member "author" for each object
lib_books[0].setAuthor ("Paulo Coalho");
lib_books[1].setAuthor ("William Goldman");
lib_books[2].setAuthor ("J.D. Salinger");
lib_books[3].setAuthor ("George Orwell");
lib_books[4].setAuthor ("Ray Bradbury");
lib_books[5].setAuthor ("F. Scott Fitzgerald");
lib_books[6].setAuthor ("James A. Mitchener");
lib_books[7].setAuthor ("Chaucer");
lib_books[8].setAuthor ("Walt Whitman");
lib_books[9].setAuthor ("Shel Silverstein");
lib_books[10].setAuthor("Homer");
lib_books[11].setAuthor("Krishnamurti");
lib_books[12].setAuthor("John Steinbeck");
lib_books[13].setAuthor("Dr. Seuss");
lib_books[14].setAuthor("Mark Twain");
The portion of main that I'm having issues:
// Function to sort the books alphabetically by author
s_sort (lib_books,n);
cout << "\n";
// For loop to print all 15 books with author and title
for(int i = 0; i < 14; i++)
{
cout <<" "<<setw(25)<<lib_books[i].getTitle()<< " " <<lib_books[i].getTitle()<< "\n" ;
}
return 0;
}
//Sort function definition
void s_sort (Book::getTitle(), int n)
{
int m;
string hold;// Initializes 'hold' as a 'string' so all the characters will be used when it is sorted
for (int k=0; k<=n-1; k++)// 'For' loop sorts through the index
{
m = k;
for (int j=k+1; j <= n-1; j++)
{
if (lib_books[j].getTitle() < lib_books[m].getTitle());
//m = j;
}
// Swaps the lib_book[].getTitle() around and uses 'hold' as a placement
hold = lib_books[m].getTitle();
lib_books[m].getTitle() = lib_books[k].getTitle();
lib_books[k].getTitle() = hold;
hold = lib_books[m].getAuthor();
lib_books[m].getAuthor() = lib_books[k].getAuthor();
lib_books[k].getAuthor() = hold;
}
}
Implementation file:
#include <iostream>
#include <cstring>
#include "Library.h"
using namespace std;
Book::Book()
{
title = " ";
author = " ";
}
string Book::getTitle()
{
return title;
}
string Book::getAuthor()
{
return author;
}
void Book::setTitle(string Title1)
{
title= Title1;
}
void Book::setAuthor(string Author1)
{
author= Author1;
}
The problem that I am having is that it doesn't sort the array. It prints out the same list that was defined. I have tried to pass the array by reference but it needs a index number in the function prototype and definition.

How to pass data through MVC for C++ (possibly using vectors or pointers)

So I have a project in which I must parse a data file, and dynamically create instances of a class Sensor while passing in the parsed data to that class. I am storing these instances in a vector of object pointers, sensors. Once the data is passed into each instance of Sensor, inside the Sensor class I must generate a reading value using the min and max values passed in from the parser. Then all of the values, min, max, type, reading, material, id must be passed to a controller class called SensorMount . This class is responsible for routing the data to a DisplayDeviceclass that I have not yet implemented.
I am confused on how to implement my controller SensorMount class. I know I need to use my get functions in the Sensor class, but I just am not sure where to start with this. Would another vector of Sensor object instances work? That is my current idea but I'm not sure if that is possible. I know sending a "message object" (Stated by my prof) could work but I can't seem to find any implementation of one online. I really appreciate any help and patience, I'm new to this and feel really stuck.
Also, I see alot of people on stack overflow condemn the use of using namespace but my professor wants us to use it. And we are not to implement a design pattern for this program (I know observer would work) , we will do that in the next.
Simulation.cpp (Where data parser is called and vector is created and initial data is passed )
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include "Simulation.hpp"
#include "EnviroSimDataParser.h"
Simulation::Simulation() {}
Simulation::~Simulation(){}
void Simulation::initializeSimulation() {
char fileName[64];
char m_sType[64];
char m_sMaterial[64];
int m_iID;
char m_sUnits[64];
double m_sMinVal;
double m_sMaxVal;
char type[64];
int IDs[8];
int IDCount;
cout << "Enter the name of the data file:" << endl;
cin >> fileName ;
//cout << fileName << "\n" ;
parser = new EnviroSimDataParser(fileName);
for (int i = 0; i < 6; i++){
parser ->getSensorData(m_sType, m_sMaterial, &m_iID, m_sUnits, &m_sMinVal, &m_sMaxVal);
sensors.push_back(new Sensor(m_sType, m_sMaterial, m_iID, m_sUnits, m_sMinVal, m_sMaxVal));
cout << "success " << m_iID << endl;
}
for (int x = 0; x <4; x++){
parser -> getDisplayData(type, IDs, &IDCount);
//if (strcmp(type, ""))
}
mount = new SensorMount();
display = new Display();
}
void Simulation::runSimulation(){
}
Sensor.cpp
#include "Sensor.hpp"
Sensor::Sensor(char *SensorType, char *SensorMaterial, int SensorID, char *SensorUnit, double MaxVal, double MinVal) {
strcpy(type, SensorType);
strcpy(material, SensorMaterial);
ID = SensorID;
strcpy(unit, SensorUnit);
max = MaxVal;
min = MinVal;
}
Sensor::Sensor(){}
Sensor::~Sensor()
{
}
double Sensor::generateReading(){
reading = min + (rand() % (int)(max - min + 1));
cout << reading<< endl;
return reading;
}
char * Sensor::getType(){
return type;
}
char * Sensor::getMaterial(){
return material;
}
int Sensor::getID(){
return ID;
}
char * Sensor::getUnit(){
return unit;
}
double Sensor::getMin(){
return min;
}
double Sensor::getMax(){
return max;
}
double Sensor::getReading(){
return reading;
}
//void Sensor::sendSensorData(){
// SensorMount.routeData(Display)
//}
Sensor.h
#ifndef Sensor_hpp
#define Sensor_hpp
#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;
class Sensor
{
public:
Sensor();
Sensor(char *SensorType, char *SensorMaterial, int SensorID, char *SensorUnit, double MaxVal, double MinVal);
~Sensor();
//virtual Sensor updateSensor();
char * getType();
char * getMaterial();
int getID();
char * getUnit();
double getMin();
double getMax();
double getReading();
private:
char type[32];
char material[32];
int ID;
int reading;
char unit[32];
double min;
double max;
double generateReading();
};
#endif /* Sensor_hpp */
SensorMount.h (controller)
#ifndef SensorMount_hpp
#define SensorMount_hpp
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <vector.
#include "Sensor.hpp"
#include "Display.hpp"
using namespace std;
class SensorMount{
private:
Sensor *sensors;
Display *displayDevices;
vectorgetSensorData;
public:
SensorMount();
~SensorMount();
};
#endif /* SensorMount_hpp */

need help on #include doesn't seem to be working

So I have a class called HPStack and I have to include it in my main class etc. However I get a "In File included from" error, what could be causing this?
Also my string objects also have errors I have have no idea why, the error is: "Unable to identifier string".
I'm new the C++ so any help would be appreciated, thanks in advance.
The error I am getting (I think) are these:
error: expected unqualified-id before "namespace"
error: expected `,' or `;' before "namespace"
error: expected namespace-name before ';' token
error: `<type error>' is not a namespace
Im not sure what I am missing but that isn't telling me much.
Here is my code: The class.h file.
#ifndef HPSTACK_H
#define HPSTACK_H
class HPStack {
public:
HPStack();
void push(double);
double pop();
double peek();
private:
double register_[4];
}
#endif
The class.cpp file.
#include "HPStack.h"
#include <cstdlib>
HPStack::HPStack() : register_{}{
}
double HPStack::push(double x) {
for (int i = 2; i >= 0; i--) {
if (isdigit(register_[i])) {
register_[i] = register_[i + 1];
}
register_[0] = x;
}
}
double HPStack::pop() {
return register_[0];
for (int i = 0; i < 3; i++) {
register_[i] = register_[i + 1];
}
}
double HPStack::peek() {
return register_[0];
}
And my main file:
#include "HPStack.h"
#include <cstdlib>
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main() {
HPStack stack;
string line;
while (getline(cin, line)) {
stringstream expression(line);
string token;
while (expression >> token) {
if (isdigit(token[0])) {
stack.push(atof(token.data()));
} else if (token == "+") {
double x = stack.pop();
double y = stack.pop();
double z = (y + x);
stack.push(z);
}
}
cout << stack.peek();
}
The error is, I'm guessing, because of this line:
double register_[4] = {};
You can not initialize class members when declaring them.
If your compiler is new enough to support C++11 features, you can use an initializer list with the constructor:
HPStack::HPStack()
: register_{}
{
}
Otherwise you have to initialize the array manually in the constructor.
And as I noted in a comment, using register_ - 2 makes no sense as it returns a pointer so the index variable i will be way beyond the end of the array.
And using register_ - 1 as the condition in the pop loop makes even less sense, as it will always be non-zero and therefore always true and the loop will loop forever.
You're missing the ; at the end of the class definition:
class HPStack {
...
}; // <== This semicolon is required

Struct defined in header and included in two source codes is only defined in one

I have a struct defined in a header file with three other files that #include that header file. One is another header(queue.h) file that defines a very basic hash table and the other two are source codes where one is defining the functions from the hash table header(queue.cpp) and the other contains main(p2.cpp).
The problem that I'm having is that the struct seems to work fine in p2.cpp but in queue.h the compiler is telling me that the struct is undefined.
Here is p2.h containing the struct definition.
#ifndef __P2_H__
#define __P2_H__
#define xCoor 0
#define yCoor 1
#include <iostream>
#include <string>
#include "queue.h"
#include "dlist.h" //linked list which I know works and is not the problem
using namespace std;
struct spot {
float key[2];
string name, category;
};
#endif /* __P2_H__ */
I have queue.h included in this header so that I only have to include p2.h in p2.cpp.
Here is p2.cpp
#include <iostream>
#include <string>
#include <iomanip>
#include "p2.h"
using namespace std;
int main () {
cout << fixed;
cout << setprecision (4);
Queue hashTable;
spot *spot1 = new spot;
spot1->key[xCoor] = 42.2893;
spot1->key[yCoor] = -83.7391;
spot1->name = "NorthsideGrill";
spot1->category = "restaurant";
hashTable.insert(spot1);
Dlist<spot> test = hashTable.find(42.2893, -83.7391);
while (!test.isEmpty()) {
spot *temp = test.removeFront();
cout << temp->key[xCoor] << " " << temp->key[yCoor] << " " << temp->name << " " << temp->category << endl;
delete temp;
}
return 0;
}
Places and item in the hash table and takes it back out.
Here is queue.h
#ifndef __QUEUE_H__
#define __QUEUE_H__
#include <iostream>
#include <string>
#include "dlist.h"
#include "p2.h"
using namespace std;
class Queue {
// OVERVIEW: contains a dynamic array of spaces.
public:
// Operational methods
bool isEmpty();
// EFFECTS: returns true if list is empy, false otherwise
void insert(spot *o);
// MODIFIES this
// EFFECTS inserts o into the array
Dlist<spot> find(float X, float Y);
// Maintenance methods
Queue(); // ctor
~Queue(); // dtor
private:
// A private type
int numInserted;
int maxElts;
Dlist <spot>** queue;
// Utility methods
//Increases the size of the queue.
void makeLarger();
int hashFunc(float X, float Y, int modNum);
};
#endif /* __QUEUE_H__ */
Here is queue.cpp
#include <iostream>
#include <string>
#include <cstdlib>
#include "queue.h"
using namespace std;
bool Queue::isEmpty() {
return !numInserted;
}
void Queue::insert(spot *o) {
if (numInserted >= maxElts) {
makeLarger();
}
int index = hashFunc(o->key[xCoor], o->key[yCoor], maxElts);
queue[index] -> insertFront(o);
}
Queue::Queue() {
numInserted = 0;
maxElts = 1000;
queue = new Dlist<spot>*[maxElts];
for (int i = 0; i < maxElts; i++) {
queue[i] = new Dlist<spot>;
}
}
Queue::~Queue() {
for (int i = 0; i < maxElts; i++) {
delete queue[i];
}
delete[] queue;
}
void Queue::makeLarger() {
Dlist <spot>** temp = queue;
queue = new Dlist <spot>*[maxElts*2];
for (int i = 0; i < maxElts*2; i++) {
queue[i] = new Dlist<spot>;
}
for (int i = 0; i < maxElts; i++) {
while (!temp[i] -> isEmpty()) {
spot *spotTemp = temp[i] -> removeFront();
int index = hashFunc(spotTemp->key[xCoor], spotTemp->key[yCoor], maxElts*2);
queue[index] -> insertFront(spotTemp);
}
}
for (int i = 0; i < maxElts; i++) {
delete temp[i];
}
delete[] temp;
maxElts *= 2;
}
int Queue::hashFunc(float X, float Y, int modNum) {
return ((int)(10000*X) + (int)(10000*Y))%modNum;
}
Dlist<spot> Queue::find(float X, float Y) {
Dlist<spot> result;
Dlist<spot> *temp = new Dlist<spot>;
int index = hashFunc(X, Y, maxElts);
while (!queue[index] -> isEmpty()) {
spot *curSpot = queue[index] -> removeFront();
if ((curSpot->key[xCoor] == X) && (curSpot->key[yCoor] == Y)) {
result.insertFront(new spot(*curSpot));
}
temp -> insertFront(curSpot);
}
delete queue[index];
queue[index] = temp;
return result;
}
I believe that the problem is in my queue.h file because it's where I get all of the errors like "spot has not been declared". Every time spot appears in queue.h I have at least one error. I searched around for anything like this but all I could find was people trying to share one instance of a struct across multiple source files, or the obvious question of putting a struct in a header and including that header across multiple source files(which is what I'm doing but my problem seems to be a rather unique one).
You are including queue.h within the header that actually defines spot, so by the point the file is actually included spot has not been defined yet.
For your scope guards, note that identifiers starting with a double underscore are reserved by the implementation, don't use them.
And this is a poor choice even in plain C:
#define xCoor 0
#define yCoor 1
use this instead:
enum {
xCoor = 0
, yCoor = 1
};
Ok first never ever using "using" clauses in header files (it destroys the purposes of namespaces)
2nd provide a complete example that fails to compile
In addition to what others have said, you also have a circular reference error, which can also lead to similar undefined symbol errors. You have queue.h include p2.h, which includes queue.h.