program executing, but not printing the correct details - c++

I have been tasked with creating a program that takes a users name / date of birth, and prints back the persons name / date of birth, age and their target heart rate.
It is driving me crazy as I can get the program to execute, but it gives me crazy answers, and I've no indication as to why.
Any advise would be greatly appreciated. Please find the code for my main.cpp / HeartRates.cpp and HeartRates.h (also attached is a screenshot of my current output).
main.cpp:
#include <iostream>
#include "HeartRates.h"
using namespace std;
int main() {
int d, m, y;
string firstName, lastName;
HeartRates heart;
cout << "Please enter your first name: ";
cin >> firstName;
heart.setFirstName(firstName);
cout << "Please enter your last name: ";
cin >> lastName;
heart.setLastName(lastName);
cout << "What year were you born: ";
cin >> y;
heart.setYearOfBirth(y);
cout << "What month were you born on: ";
cin >> m;
heart.setMonthOfBirth(m);
cout << "What day were you born on: ";
cin >> d;
heart.setDayOfBirth(d);
int age = heart.getAge();
int maxHR = heart.getMaxHeartRate(age);
heart.displayHeartRates(age);
heart.getTargetHeartRate(maxHR);
}
HeartRates.h:
#include <string>
class HeartRates {
public:
explicit HeartRates();
HeartRates(std::string firstname, std::string lastname, int day, int month, int year);
void setFirstName(std::string); //set 1st name
void setLastName(std::string); //set 2nd name
void setDayOfBirth(int); //set 'day' of birth
void setMonthOfBirth(int); //set 'month' of birth
void setYearOfBirth(int); //set 'year' of birth
std::string getFirstName() const; //get 1st name
std::string getLastName() const; //get last name
int getDayOfBirth() const; //get Day of Birth
int getMonthOfBirth() const; //get Month of Birth
int getYearOfBirth() const; //get Year of Birth
int getAge(); //Function to get and return age
int getMaxHeartRate(int); //Function to get max heart rate
void getTargetHeartRate(int); //Function to get target heart rate
void displayHeartRates(int); //Function to display heart rate
public:
std::string firstName;
std::string lastName;
int dayOfBirth;
int monthOfBirth;
int yearOfBirth;
};// terminate
HeartRates.cpp:
#include <iostream>
#include "HeartRates.h"
using namespace std;
// default constructor
HeartRates::HeartRates() {
std::string firstName = "unknown";
std::string lastName = "unknown";
int dayOfBirth = 0;
int monthOfBirth = 0;
int yearOfBirth = 0;
}// end default constructor
//2nd constructor
HeartRates::HeartRates(std::string firstname, std::string lastname, int day, int month, int year) {
string setFirstName(firstname);
string setLastName(lastname);
int setDayOfBirth(day);
int setMonthOfBirth(month);
int setYearOfBirth(year);
}// end 2nd constructor
//1st name function
void HeartRates::setFirstName(string firstname) {
string firstName = firstname;
}//end 1st name function
//last name function
void HeartRates::setLastName(string lastname) {
string lastName = lastname;
}//end last name function
// set day of birth
void HeartRates::setDayOfBirth(int day) {
int dayOfBirth = day;
}//end day of birth function
//set month of birth
void HeartRates::setMonthOfBirth(int month) {
int monthOfBirth = month;
}//end month of birth function
//set year of birth
void HeartRates::setYearOfBirth(int year) {
int yearOfBirth = year;
}//end year of birth
// get 1st name function
string HeartRates::getFirstName() const {
return firstName;
}// end 1st name function
// get last name function
string HeartRates::getLastName() const {
return lastName;
}// end last name function
// get day of birth function
int HeartRates::getDayOfBirth() const {
return dayOfBirth;
}//end day of birth function
// get month of birth function
int HeartRates::getMonthOfBirth() const {
return monthOfBirth;
}//end month of birth function
// get year of birth function
int HeartRates::getYearOfBirth() const {
return yearOfBirth;
}//end year of birth function
//Calculate age function
int HeartRates::getAge() {
int age;
int d;
int m;
int y;
cout << "enter current year: \n" << endl;
cin >> y;
cout << "enter current month: \n" << endl;
cin >> m;
cout << "Enter current day: \n" << endl;
cin >> d;
if (getMonthOfBirth() < m) {
m = m - getMonthOfBirth();
} else {
m = getMonthOfBirth() - m;
}
if (getDayOfBirth() < d) {
d = d - getDayOfBirth();
} else {
d = getDayOfBirth() - d;
}
age = y - getYearOfBirth();
return age;
} //end calculate age function
//calculate max heart rate function
int HeartRates::getMaxHeartRate(int age) {
//220 - age
int maxHR = 220 - age;
return maxHR;
}//end max heart rate function
//calculate target heart rate function
void HeartRates::getTargetHeartRate(int maxHR) {
// target heart rate is between 50% & 85% of maximum heart rate
cout << "Your target heart rate is between " << maxHR * 0.5 << " and " << maxHR * 0.85 << "bpm. ";
}//end of target heart rate function
// display info function
void HeartRates::displayHeartRates(int age)
{
int a = age;
cout << "Hello " << getFirstName() << " " << getLastName() << endl;
cout << "Your DOB is " << getDayOfBirth() << "/" << getMonthOfBirth() << "/" << getYearOfBirth() <<
endl;
cout << "Your age is " << a << "years old" << endl;
} // end display info function

Remove the type with this in the setters.
for example:
void HeartRates::setDayOfBirth(int day) {
int dayOfBirth = day;
}//end day of birth function
int dayOfBirth = day; make a new variable with the name of dayOfBirth and not update the field of the class.
To update the field of the class you don't need to write the type of the variable.
like that: (It is fine to add this)
void HeartRates::setDayOfBirth(int day) {
this->dayOfBirth = day;
}//end day of birth function

Accessing member variables
You seem to confuse variable declaration with assigning values to member variables.
void HeartRates::setMonthOfBirth(int month) {
int monthOfBirth = month;
}
In the above, you declare a local variable named monthOfBirth, assign the value of the variable month to it and at the end of the method scope, it gets destroyed and nothing else happens. You need the following instead:
void HeartRates::setMonthOfBirth(int month) {
monthOfBirth = month;
// or
this->monthOfBirth = month;
}
Constructing your object
Your constructor does not initialize the member variables at all. It should be like this:
HeartRates::HeartRates(): firstName("unknown"), lastName("unknown"), dayOfBirth(0), monthOfBirth(0), yearOfBirth(0)
{}

Related

Exception has occured, unknown signal error when using class object again inside each function

I'm trying to write a C++ code for a course I'm enrolled in, where I keep the information of the students enrolled in the course.
I should be able to add a student to the classrrom in the user interface written in main , by calling the function void addNewStudent(int ID, string name, string surname), where I create my object instances, Student, and Course inside the function.
I should also be able to search by given ID by calling the function void showStudent(int ID) in the main, where the function uses the getStudent(ID) method of the object of the classCourse
I did not write all the methods, but when I try to debug this code, I got the error " Exception has occured, unknown signal error."
My questions are:
What is the reason of this error? How can I fix it?
Suppose that the user interface in the main is necessary to use as well as the functions it calls. Do I have to create a class object again inside each function as I wrote?
Can a more effective implementation be made in accordance with the object oriented principles I have defined above?
#include <iostream>
using namespace std;
#define MAX 10
class Student {
private:
int ID;
string name;
string surname;
public:
Student()
{
ID = 0;
string name = "" ;
string surname = "";
}
void setID(int ID_set);
int getID();
void setName(string name_set);
string getName();
void setSurName(string surname_set);
string getSurName();
};
class Course {
private:
Student students[MAX];
int num =0 ; // The current number of students in the course, initially 0.
float weightQ;
float weightHW;
float weightF;
public:
Course()
{
students[num] = {};
weightQ = 0.3;
weightHW = 0.3;
weightF = 0.4;
}
int getNum(); // Returns how many students are in the course
void addNewStudent(Student new_student);
void updateWeights(float weightQ_update, float weightHW_update, float weightF_update);
void getStudent(int ID_given);
};
// Method declerations for the class Student
void Student :: setID(int ID_set){
ID = ID_set;
}
int Student :: getID(){
return ID;
}
void Student :: setName(string name_set){
name = name_set;
}
string Student :: getName(){
return name;
}
void Student :: setSurName(string surname_set){
surname = surname_set;
}
string Student :: getSurName(){
return surname;
}
// Method declerations for the class Course
int Course :: getNum(){
return num;
}
void Course :: addNewStudent(Student new_student){
students[num] = new_student ;
num = num + 1;
}
void Course :: updateWeights(float weightQ_update, float weightHW_update, float weightF_update){
weightQ = weightQ_update;
weightHW = weightHW_update;
weightF = weightF_update;
}
void Course :: getStudent(int ID_given){
for(int i = 0; i<MAX; i++){
if(ID_given == students[i].getID()){
cout << "Student Name & Surname : " << students[i].getName() << " " << students[i].getSurName()<<"\n";
}
}
}
void addNewStudent(int ID, string name, string surname){
Student student;
Course ECE101;
student.setID(ID);
student.setName(name);
student.setSurName(surname);
ECE101.addNewStudent(student);
}
void showStudent(int ID){
Course ECE101;
ECE101.getStudent(ID);
}
int main(){
Course ECE101;
cout << "Welcome to the ECE101 Classroom Interface"<<"\n";
cout << "Choose your option\n";
string option_1 = "1) Add a student ";
string option_2 = "2) Search a student by ID";
cout << "Enter your option: ";
int x;
int ID;
string name, surname;
cin >> x;
if (x == 1)
cout << "Enter the student ID ";
cin >> ID;
cout << endl;
cout << "Enter the student name ";
cin >> name;
cout << endl;
cout << "Enter the student surname " ;
cin >> surname;
addNewStudent(ID, name, surname);
return 0;
}
 To make the menu more interactive you could add a do while statement that would accept 3 options:
register
show data
exit
int main(){
Course ECE101;
int x;
int ID;
string name, surname;
string option_1 = "1) Add a student\n";
string option_2 = "2) Search a student by ID\n";
cout << "Welcome to the ECE101 Classroom Interface\n";
cout << "Choose your option\n";
cout << option_1 << option_2;
cin >> x;
do {
if (x == 1) {
cout << "Enter the student ID ";
cin >> ID;
cout << endl;
cout << "Enter the student name ";
cin >> name;
cout << endl;
cout << "Enter the student surname " ;
cin >> surname;
addNewStudent(ID, name, surname, ECE101);
}
else {
cout << "Enter the student ID\n";
cin >> ID;
showStudent(ID, ECE101);
}
cout << "Choose your option\n";
cin >> x;
} while(x != 3);
return 0;
}
addnewStudent() and showStudent() methods now accepts an instance of Course as an argument to be able to add students.
void addNewStudent(int ID, string name, string surname, Course &course) {
Student student;
student.setID(ID);
student.setName(name);
student.setSurName(surname);
course.addNewStudent(student);
}
void showStudent(int ID, Course &course) {
course.getStudent(ID, course);
}
the function is modified from the same class as well.
void Course::getStudent(int ID_given, Course &course) {
for(int i = 0; i<MAX; i++){
if(ID_given == students[i].getID()){
cout << "Student Name & Surname : " << students[i].getName() << " " << students[i].getSurName()<<"\n";
}
}
}
Demo
Your addNewStudent function creates a new course everytime it is called. You could pass a reference to the course as a parameter into the function and call Course.addNewStudent(student). You'll want to make sure you specify it's a reference though when you define your function or you'll just create a copy of the course.

To find max salary using friend function of a class having employee details(name,ID, position,salary) and print max salary details

#include <iostream.h>
#include <conio.h>
class Employee{
int Id;
string Name;
string Post;
public:
long int Salary;
void GetDetails();
void DisplayDetails();
friend void MaxSalary();
};
void Employee::GetDetails(){
cout << "\nEnter Employee Id : ";
cin >> Id;
cout << "\nEnter Employee Name : ";
cin.ignore();
getline(cin,Name);
cout << "\nEnter Employee Post : ";
cin.ignore();
getline(cin,Post);
cout << "\nEnter Employee Salary : ";
cin >> Salary;
}
void Employee::DisplayDetails(){
cout << "\nEmployee Id : " << Id;
cout << "\nEmployee Name : " << Name;
cout << "\nEmployee Post : " << Post;
cout << "\nEmployee Salary : " << Salary;
}
void MaxSalary(Employee a[], int x){
long int max;
for(int j=0; j<x; j++){
if(a[j].Salary>a[j+1].Salary)
max=a[j].Salary;
}
cout<<"Maximum Salary = "<<max<<endl;
}
int main()
{
int n, i;
cout<<"Enter Number of Employees : ";
cin>>n;
Employee E[n];
cout<<"\n\n----------ENTER DETAILS OF EMPLOYEES----------\n\n";
for(i=0;i<n;i++){
cout<<"\n\n Enter details of Employee "<<i+1<<endl;
E[i].GetDetails();
}
cout<<"\n\n----------DETAILS OF EMPLOYEES----------\n\n";
for(i=0;i<n;i++){
cout<<"\n\n Details of Employee "<<i+1<<endl;
E[i].DisplayDetails();
}
MaxSalary(E[n], n );
return 0;
}
There are lots of defects in the given code:
The variable length arrays (VLAs) are not allowed in C++. In other words, the syntax:
cin >> x;
Employee emp[x];
is invalid. Note that C99 is an exception in this case.
In the For loop of MaxSalary(), a[j + 1] is given, it will access out-of-bounds array, which invokes an undefined behavior.
Declaring a variable in a class as public breaks the rule of OOP:
public:
long int Salary; // Not a good idea
You do not need to pass [n] as the function argument:
MaxSalary(E[n], n);
The refined code would look like:
#include <iostream>
#include <limits>
#include <vector>
// Using this statement in order to reduce the spam of 'std::' here
using namespace std;
class Employee {
int ID;
string name;
string post;
long int salary;
public:
Employee() {}
// Initializing the class object
void initEmployee(int id, string varName, string varPost, long sal) {
ID = id, \
name = varName, \
post = varPost, \
salary = sal;
}
// 'salary' getter
long getSalary() {
return salary;
}
// The friend function
friend void maxSalary(vector<Employee> data) {
int max = 0;
for (size_t i{1}, len = data.size(); i < len; i++)
// Comparison
if (data[i].getSalary() > data[i - 1].getSalary())
max = data[i].getSalary();
// After the loop execution, prints the maximum salary
std::cout << "Maximum salary: " << max << endl;
}
};
int main(void) {
int total;
cout << "Enter the total number of employees: ";
cin >> total;
vector<Employee> emp(total);
for (int i{}; i < total; i++) {
// Temporary variables to store data in each iteration
Employee temp;
string tempName;
string tempPost;
int tempID;
long int tempSal;
cout << "Name of the employee " << i + 1 << ": ";
getline(cin, tempName);
// Clearing the 'cin' in order to prevent the getline skips
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Post of the employee: ";
getline(cin, tempPost);
cout << "Employee ID: ";
cin >> tempID;
cout << "Total salary: ";
cin >> tempSal;
// Initializing the temporary object
temp.initEmployee(tempID, tempName, tempPost, tempSal);
// Pushing the object into the main vector
emp.push_back(temp);
}
// Comparing the vector elements (note: it is a friend function)
maxSalary(emp);
return 0;
}
As a test case:
Enter the total number of employees: 2 // Number of employees
Name of the employee 1: John Doe // Employee 1
Post of the employee: Manager
Employee ID: 100
Total salary: 15000
Name of the employee 2: Max Ville // Employee 2
Post of the employee: Assitant Manager
Employee ID: 102
Total salary: 50000
Maximum salary: 50000 // Maximum salary

In C++ is there a way for me to have a function without passing an argument?

I have to write a code that outputs a formatted date when the user inputs 3 integers but also outputs a default date of 1/1/2019. I'm supposed to use a class and objects for this but i can't figure out how to get it to work without any arguments being passed from the object. Here's my current code
class Date
{
private:
int defaultDay = 1;
int defaultMonth = 1;
int defaultYear = 2019;
public:
Date()
{
int day = defaultDay;
int month = defaultMonth;
int Year = defaultYear;
}
void dateFormat(int day,int month,int year)
{
defaultDay = day;
defaultMonth = month;
defaultYear = year;
cout << day << "/" << month << "/" << year << endl;
}
}
int main()
{
Date setDate,
int day, month, year;
cin >> day;
while(day < 1 || day > 31)
{
cout << "Please enter a number between 1 and 31" << endl;
cin >> day;
}
cin >> month;
while(month < 1 || month > 12)
{
cout << "Please enter a number between 1 and 12" << endl;
cin >> month;
}
cin >> year;
setDate.dateFormat(day, month, year);
return 0;
}
I'm going to make minimal changes to your code to show you some things you can do.
class Date
{
private:
int day = 1;
int month = 1;
int year = 2019;
public:
// Default constructor with no arguments.
Date()
{
}
// Constructor with arguments.
Date(int _day, int _month, int _year)
{
day = _day;
month = _month;
year = _year;
}
//print me.
void print() const {
cout << day << "/" << month << "/" << year << endl;
}
}
Date firstDate(); // Will use defaults
Date secondDate(1, 11, 2019); // November 11, 2019
Here's what I did... First, I renamed your fields. You don't need defaultDay etc unless you have another reason for them.
Next, I gave you two constructors, one with no arguments (called the default constructor), and one with arguments. Classes can have as many constructors as you want, as long as the signatures are different.
Then I made a print method.
I hope this helps.

Function call error with my class

This program is supposed to prompt the user for two different employees and print their name, last name, ssn, payrate, and total pay for the week. Also it should determine if the worker worked any over time hours and recalculate their pay if they do.
I keep getting this error message:
No matching function call to Employee::Employee()
I will mark the lines which this message appears with a // *****.
The message appears 3 times. Please review my issues and help me fix them, and also explain what you did to fix them.
#include <cstdlib>
#include <iostream>
#include <math.h>
/*
Name: Employee2
Author: --------
Date: 20/10/14 20:36
Description: A program that prints workers info using classes
*/
using namespace std;
class Employee
{
private:
string firstname, lastname, ssn;
int payRate, hours;
public:
//A Four Parameter Constructor
Employee (string newFirst, string newLast, string newSsn, int newpayRate, int newHours)
{
firstname = newFirst;
lastname = newLast;
ssn = newSsn;
payRate = newpayRate;
hours = newHours;
}
//Setter or Mutator Functions
void setnewFirst(string newFirst)
{
firstname = newFirst;
}
void setnewLast(string newLast)
{
lastname = newLast;
}
void setnewSsn(string newSsn)
{
ssn = newSsn;
}
void setnewpayRate(int newpayRate)
{
payRate = newpayRate;
}
void setnewHours(int newHours)
{
hours = newHours;
}
void setEmployee(string newFirst, string newLast, string newSsn, int newpayRate, int newHours)
{
firstname = newFirst;
lastname = newLast;
ssn = newSsn;
payRate = newpayRate;
hours = newHours;
}
//Accessor Functions
string getfirstname ()
{
return firstname;
}
string getlastname ()
{
return lastname;
}
string getssn ()
{
return ssn;
}
int getpayRate ()
{
return payRate;
}
int gethours ()
{
return hours;
}
//Output Functions
void printEmployee ()
{
cout << firstname << " " << lastname << endl << ssn << endl << payRate << endl << hours << endl;
}
//Functions to use employee info
Employee newEmployee ()
{
Employee e1; //**************
string newFirst;
string newLast;
string newSsn;
int newpayRate;
int newHours;
cout << "Enter First Name: " ;
cin >> newFirst;
cout << "Enter Last Name: " ;
cin >> newLast;
cout << "Enter SSN: " ;
cin >> newSsn;
cout << "Enter Payrate: " ;
cin >> newpayRate;
cout << "Enter Hours Worked: " ;
cin >> newHours;
e1.setnewFirst(newFirst);
e1.setnewLast(newLast);
e1.setnewSsn(newSsn);
e1.setnewpayRate(newpayRate);
e1.setnewHours(newHours);
return e1;
}
//Function to Calculate Weekly Pay
int calculatePay (int hours)
{
double result;
if ( hours > 40 )
{
result = (hours - 40) * (payRate * 1.5) + (40 * payRate);
}
else
{
result = (hours * payRate);
}
}
};
Employee newEmployee();
//Main
int main(int argc, char *argv[])
{
Employee firstEmployee; // *********************
Employee secondEmployee; // *********************
double result;
firstEmployee = firstEmployee.newEmployee();
secondEmployee = secondEmployee.newEmployee();
cout << "First Employee Pay: " ;
firstEmployee.printEmployee();
cout << endl;
cout << "Secnod Employee Pay: " ;
secondEmployee.printEmployee();
system("PAUSE");
return EXIT_SUCCESS;
}
A constructor is intended to operate on the space in which the new object is being created. This means you don't need to complicate things by creating the additional object e1. Remove the problematic line:
Employee e1; //**************
Remove all e1 references from your code; for example change
e1.setnewFirst(newFirst);
e1.setnewLast(newLast);
e1.setnewSsn(newSsn);
e1.setnewpayRate(newpayRate);
e1.setnewHours(newHours);
to:
setnewFirst(newFirst);
setnewLast(newLast);
setnewSsn(newSsn);
setnewpayRate(newpayRate);
setnewHours(newHours);
Constructors do not return values; remove:
return e1;
Compile, test, debug, rinse, and repeat.

Localize my Constructor

class Student
{
private:
string name;
int year;
string semester;
int AmtClass;
static string Year[4];
public:
Student();
Student(int AmtClass);
Student(Student &);
void setName(string name);
void setYear(int year);
void setSemester(string semester);
void setAmtClass(int AmtClass);
string getName();
int getYear();
string getSemester();
int getAmtClass();
~Student()
{
if(AmtClass > 0)
delete [] course;
}
};
string Student::Year[4] = { "Freshman", "Sophomore", "Junior", "senior" };
Student::Student()
{
name = "";
year = 0;
semester = "";
AmtClass = 0;
}
Student::Student(int amount)
{
AmtClass = amount;
string *pName;
pName = new string[AmtClass];
for(int i = 0; i < AmtClass; i++)
{
pName[i] = "";
}
}
Skipping Accessors and Mutator functions...
void readStudentData(Student &);
void printStudentData(Student);
int main()
{
int amount;
cout << "How many courses are you currently taking? ";
cin >> amount;
Student kid;
kid.setAmtClass(amount);
readStudentData(kid);
}
void readStudentData(Student &kid)
{
cin.ignore(10000, '\n');
int amount = kid.getAmtClass();
string name = "";
string semester = "";
int year = 0;
cout << "What is your full name? ";
getline(cin,name);
cout << "\nHow many years have you been in college? ";
cin >> year;
cout << "\nWhat is your current semester? ";
getline(cin,semester);
Student kid1(amount);
cout << "Please enter the name of all your courses." << endl;
for(int i = 0; i < amount; i++)
{
cout << "Course #" << i+1 << " : ";
getline(cin,pName[i]);
}
}
Okay edited this program a bit after realizing my pName is a local variable in the constructor...I am supposed to create a constructor that received an integer parameter corresponding to the number of courses the student is taking.The function dynamically allocates the string array of courses and sets each element to "". And then I am supposed to use this to record the names of the courses the student is taking.
The Year array should simply be allocated to the amount, and that's it:
Student::Student(int amount)
: Year(new std::string[amount]()), AmtClass(amount)
{
}
You can also use std::vector for this so you do not have to deal with deleting the memory yourself:
class Student
{
std::vector<std::string> Year;
// ...
};
Student::Student(int amount)
: Year(amount), AmtClass(Year.size())
{
}