Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
The community is reviewing whether to reopen this question as of 2 months ago.
Improve this question
So i am practicing header files and implementation files for c++ and i cannot seem to display the letter grade for this program. Everything else is working as it should and displaying the correct data except for the letter grade. I have been trying to figure it out and i think it may be something so simple that i am missing but i need an extra set of eyes. i would really appreciate the help!
//Main program
#include <iostream>
#include <string>
#include "studentType.h"
using namespace std;
int main()
{
studentType student;
studentType newStudent("Brain", "Johnson", '*', 85, 95, 3.89);
student.print();
cout << "***************" << endl << endl;
newStudent.print();
cout << "***************" << endl << endl;
return 0;
}
Header File:
#include <string>
using namespace std;
class studentType
{
private:
string firstName;
string lastName;
int grade;
int average;
char courseGrade;
int testScore;
int progScore;
double GPA;
public:
studentType(string fn = "", string ln = "", char courseGrade = '*', int tscore = 0, int pscore = 0, double gpa = 0);
string getFirstName() const;
string getLastName() const;
int getGrade();
char getCourseGrade() const;
int getTestScore() const;
int getProgScore() const;
double getGPA() const;
void setFirstName(string fn);
void setLastName(string ln);
void setGrade();
void setCourseGrade(char courseGrade);
void setTestScore(int tscore);
void setProgScore(int pscore);
void setGPA(double gpa);
void print();
};
Implementation file:
#include <iostream>
#include <string>
#include <iomanip>
#include "studentType.h"
using namespace std;
studentType::studentType(string fn, string ln, char courseGrade, int tscore, int pscore, double gpa)
{
firstName = fn;
lastName = ln;
courseGrade = courseGrade;
testScore = tscore;
progScore = pscore;
GPA = gpa;
}
string studentType::getFirstName() const
{
return firstName;
}
string studentType::getLastName() const
{
return lastName;
}
int studentType::getGrade()
{
return grade;
}
char studentType::getCourseGrade() const
{
return courseGrade;
}
int studentType::getTestScore() const
{
return testScore;
}
int studentType::getProgScore() const
{
return progScore;
}
double studentType::getGPA() const
{
return GPA;
}
void studentType::setFirstName(string fn)
{
firstName = fn;
}
void studentType::setLastName(string ln)
{
lastName = ln;
}
void studentType::setGrade()
{
int average = (testScore + progScore) / 2;
if(average >= 90){
courseGrade = 'A';
}
else if(average >= 80){
courseGrade = 'B';
}
else if(average >= 70){
courseGrade = 'C';
}
else if(average >= 60){
courseGrade = 'D';
}
else{
courseGrade = 'F';
}
}
void studentType::setCourseGrade(char courseGrade)
{
courseGrade = courseGrade;
}
void studentType::setTestScore(int tscore)
{
testScore = tscore;
}
void studentType::setProgScore(int pscore)
{
progScore = pscore;
}
void studentType::setGPA(double gpa)
{
GPA = gpa;
}
void studentType::print()
{
cout << "Name: " << firstName << " " << lastName << endl;
cout << "Grade: " << courseGrade << endl;
cout << "Test Score: " << testScore << endl;
cout << "Programming Score: " << progScore << endl;
cout << "GPA: " << GPA << endl;
}
I think it has something to do with the constructor like adding my grade() function but to be honest my brain is fried and i just need some help i have been staring at this for way to long...
You are never calling setGrade(). Maybe you should call it in the class's constructor?
Displaying grade has nothing to do with header/implementation files.
grade is not initialized in the constructor, so it will have some garbage value. The grade is getting computed only in setGrade() method hence you need to call this method from the constructor to update the grade member variable.
Update your constructor to the following to get the correct result.
studentType::studentType(string fn, string ln, char courseGrade, int tscore, int pscore, double gpa)
{
firstName = fn;
lastName = ln;
courseGrade = courseGrade;
testScore = tscore;
progScore = pscore;
GPA = gpa;
setGrade(); // compute grade based on scores
}
Related
For my project, my program has to read a file that looks like this: "Mary", "000111222", "Junior", 12, 4.0
In my main code it can read it, but only as strings only. I want it to read it as string,string, string, float, float. The getLine() method only works with strings. I tried other ways but it did not work. Any suggestions? The fields I want to be a float is gpa and credit. Any advice is appreciated! Thank you!
#include <iostream>
#include <string>
#include <iterator>
#include <iomanip>
#include <fstream>
#include <vector>
include <sstream>
#include <algorithm>
using namespace std;
class Student {
//declare local variables
protected:
string name; //people with names longer than 21 characters will just have
to make do
string ssn; // Social Secturity Number.
string gpa; //Most up to date gpa for the student
string credits; //Number of student's credit hours
//build public methods
public:
//Default Constructor
Student() {}
//Student constructor. Besides the character arrays, everything else is
passed by reference.
Student(const string n, const string s, string sGPA, string sCredits) {
name = n;
ssn = s;
gpa = sGPA;
credits = sCredits;
}
string getName() {
return name;
}
string getSSN() {
return ssn;
}
string getGPA() {
return gpa;
}
string getCredit() {
return credits;
}
//a function that is expected to be implemented and overridden by subclasses
virtual void print() const {
cout << '\n' << endl;
cout << "Student's name: " << name << endl;
cout << "Student SSN: " << ssn << endl;
cout << "Student's current GPA: " << gpa << endl;
cout << "Student's credit hours: " << credits << endl;
}
// a pure virtual function for implementation later. Makes whole class
Abstract
virtual float tuition() const = 0;
};
class Undergrad : public Student {
//declare local variables
protected:
float undergrad_rate = 380.0;
string year;
//build public methods
public:
//Default Constructor
Undergrad() {}
//Undergrad Constructor
Undergrad(const string n, const string s, string uGPA, string uCredits,
string y) :
Student(n, s, uGPA, uCredits), year(y) {}
//Display the contents of undergrad
void print() const {
Student::print();
cout << "Undergrad Rate: " << undergrad_rate << endl;
cout << "Year: " << year << endl;
}
//Display undergrad's current year
string get_year() {
return year;
}
//Display the undergrad's current rate
float get_rate() {
return undergrad_rate;
}
//Set a undergrad's current year
void set_year(string y) {
year = y;
}
//Display the cost for an undergrad to attend university
float tuition() const {
return 1000000;
}
};
int main() {
ifstream ip("data.txt");
if (!ip.is_open()) std::cout << "ERROR: File not found" << '/n';
string name;
string ssn;
string year;
string credit;
string gpa;
vector<Undergrad> file;
//Undergrad g(name, ssn, year, credit, gpa);
while (ip.good()) {
getline(ip, name, ',');
getline(ip, ssn, ',');
getline(ip, gpa, ',');
getline(ip, credit, ',');
getline(ip, year, '\n');
// float number = stoi(gpa);
//float number1 = stoi(credit);
Undergrad g(name, ssn, year, credit, gpa);
file.push_back(g);
}
ip.close();
Undergrad g = file.back();
file.pop_back();
file.insert(file.begin(),g);
for (int i = 0; i < file.size(); i++) {
cout << "Name: " << file[i].getName() << endl;
cout << "SSN: " << file[i].getSSN() << endl;
cout << "Year: " << file[i].get_year() << endl;
cout << "Credit: " << file[i].getCredit() << endl;
cout << "GPA " << file[i].getGPA() << endl;
cout << " " << endl;
}
system("pause");
return 0;
}
You can cast the string to a float using atof. See reference here. Be sure to include <cstdlib>. Your constructor would look like:
Student(const string n, const string s, string sGPA, string sCredits) {
name = n;
ssn = s;
gpa = (float)atof(sGPA.c_str());
credits = (float)atof(sCredits.c_str());
}
I am new to C++ and I am writing a program that is supposed to simulate a colony of bunnies. The program will be able to add them, give them names, ages, colors, etc. Right now I have a working program that will add bunnies after each pass and age them by 1. How could I make the program delete a bunny once the bunny reaches age 10.
The code:
enter code here
#include <iostream>
#include <ctime>
#include <vector>
#include <cstdlib>
#include <limits>
using namespace std;
const int POSSIBLE_NAMES = 18;
const int POSSIBLE_COLORS = 4;
static std::string possibleNames[] ={
"Jen",
"Alex",
"Janice",
"Tom",
"Bob",
"Cassie",
"Louis",
"Frank",
"Bugs",
"Daffy",
"Mickey",
"Minnie",
"Pluto",
"Venus",
"Topanga",
"Corey",
"Francis",
"London",
};
static std::string possibleColors[] ={
"White",
"Brown",
"Black",
"Spotted"
};
struct Bunny
{
public:
string name;
int age;
string color;
char sex;
Bunny(){
setSex();
setColor();
setAge(0);
setName();
}
int randomGeneration(int x){
return rand() % x;
srand (time(NULL));
}
void setSex()
{
int randomNumber = randomGeneration(2);
( randomNumber == 1 ) ? sex = 'm' : sex = 'f';
}
char getSex()
{
return sex;
}
void setColor()
{
int randomNumber = randomGeneration(POSSIBLE_COLORS);
color = possibleColors[randomNumber];
}
string getColor()
{
return color;
}
void setAge(int age)
{
this->age = age;
}
int getAge()
{
age++;
return age;
}
void setName()
{
int i = randomGeneration(POSSIBLE_NAMES);
name = possibleNames[i];
}
string getName()
{
return name;
}
void deleteBunny(){
if (age > 10){
cout << getName() << " has died" << endl;
}
}
void printBunny()
{
cout << "Name: " << getName() << endl;
cout << "Sex: " << getSex() << endl;
cout << "Color: " << getColor() << endl;
cout << "Age: " << getAge() << endl;
}
};
int main()
{
vector< Bunny > colony;
char quit = '\0';
do
{
// Add more bunny
for (int i = 0; i < 5; i++)
{
colony.push_back(Bunny());
}
// Print all the bunny
for (int i =0; i < colony.size(); i++)
{
colony[i].printBunny();
colony[i].deleteBunny();
cout << endl;
}
cout << "You have a total of " << colony.size() << " bunnies\n";
cout << "Press a key to add more bunny, q to quit\n";
quit = cin.get();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// repeat
} while (quit != 'q' && quit != 'Q');
return 0;
}
You have to use erase remove idiom:
std::erase(colony.remove_if( colony.begin(), colony.end(),
[] (bunny& oldBunny){ return oldBunny.age > 10; } ), colony.end());
Each pass you need to check if been is over ten and delete them from the vector.
vector< Bunny > colony;
do
{
for(int i = 0; i < colony.size(); i++){
if(colony[i].getAge() > 10) {
// Call your delete function
colony[i].deleteBunny();
// Delete from vector
colony.erase(colony.begin() + i);
// Shift vector back down
i--;
}
}
// Add more bunny
// Rest of code
}
I have recently tried to learn how to create an object of vectors in order to represent objects of students including their names and grades. but when I wrote my program I got some errors regarding using &. I do not know what is the problem with my errors. could you please help me to fix it?
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void printvector(const vector< student>&); // fill vector.fill in student information
void fillvector(vector< student>&); // print the information of all students
class student {
public:
student();
student(string, char);
~student();
string getName() ;
char getGrade() ;
void setName(string);
void setGrade(char);
private:
string newName;
char newGrade;
};
student::student() { newGrade = ' '; }
student::student(string name, char grade) {
newName = name;
newGrade = grade;
}
student::~student(){ }
string student::getName() { return newName; }
char student::getGrade() { return newGrade; }
void student::setName(string name) { newName = name; }
void student::setGrade(char grade) { newGrade = grade; }
int main() {
vector<student> myclass;
printvector(myclass);
fillvector(myclass);
return 0;
}
void fillvector(vector< student>& newmyclass) {
string name;
char grade;
int classsize;
cout << "how many students are in your class?";
cin >> classsize;
for (int i = 0; i < classsize; i++) {
cout << "enter student name";
cin >> name;
cout << "enter student grade";
cin >> grade;
student newstudent(name, grade);
newmyclass.push_back(newstudent);
cout << endl;
}
}
void printvector( vector< student>& newmyclass) {
unsigned int size = newmyclass.size();
for (unsigned int i = 0; i < size; i++) {
cout << "student name:" << newmyclass[i].getName() << endl;
cout << endl;
cout << "student grade" << newmyclass[i].getGrade() << endl;
cout << endl;
}
}
It seems you're printing your vector before filling it.. Is your problem fixed when you swap them around?
int main() {
vector<student> myclass;
printvector(myclass); // <--- These two lines should probably be swapped
fillvector(myclass); // <---
return 0;
}
Generally I have a class named "person" and its methods, print: to print the data, and is_better_than to find some max numbers. I cannot understand what is the problem. Any advice?
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
class person
{
private:
string name;
double weight;
double height;
public:
person(); //Constructor
bool is_better_than(person best);
void read();
void print();
void operator=(const person& b); //overloading operator
};
person::person()
{
string name = "";
double weight = 0;
double height = 0;
}
void person::print()
{
cout << name << "\nWeight: " << weight << "\nHeight: " << height << "\n";
}
void person::read()
{
cout << "Please enter person's name: ";
getline(cin, this->name);
cout << "Please enter person's weight: ";
cin >> this->weight;
cout << "Please enter person's height: ";
cin >> this->height;
string remainder;
getline(cin, remainder); //clear the buffer
}
bool person::is_better_than(person best)
{
if ((this->weight / pow(this->height,2) >= best.weight / (pow(best.height,2))) || best.weight == 0)
return true;
return false;
}
// iperfortosi telesti =
void person::operator=(const person & b)
{
this->name = b.name;
this->weight = b.weight;
this->height = b.height;
}
int main()
{
person maxBMI;
bool cont = true;
while (cont)
{
person newperson;
newperson.read();
if (newperson.is_better_than(maxBMI))
maxBMI = newperson;
cout << "More data? (y/n) ";
string answer;
getline(cin, answer);
if (answer != "y")
cont = false;
}
cout << "The person with maximum BMI (body mass index) is ";
maxBMI.print();
return 0;
}
Output:
Please enter person's name: Name
Please enter person's weight: 123
Please enter person's height: 123
More data? (y/n) n
The person with maximum BMI (body mass index) is
Weight: 1.7881e-307
Height: 2.0746e-317
Your default constructor does not work because it assigns to local variables and not to class variables. It should look like this:
person::person()
{
name = "";
weight = 0;
height = 0;
}
or better:
person::person() : name(""), weight(0.0), height(0.0) {}
With your default constructor, the class attributes remain uninitialized and the assumption that best.weightis initially zero, does not work.
Hello there stackOverflow.
I am a noob when it comes to c++ and today i tried to compile my first program including classes. This ofcourse gave me an error and i don't really know what i did wrong since its my first time compling a class program :P
i tried to google it and it said something about either the DLL.'s are building wrong? (i got it all in debug mode, so it can't be that). So the other option is: i might be freeing the memory wrongly or something like that, can anyone explain where i did wrong?
i tried to compare the code to the tutorial i found. But that didn't help. (the tutorial im referring to is: http://www.youtube.com/watch?v=vz1O9nRyZaY ). The error i'm getting is
void __cdecl _free_base (void * pBlock)
{
int retval = 0;
if (pBlock == NULL)
return;
RTCCALLBACK(_RTC_Free_hook, (pBlock, 0));
retval = HeapFree(_crtheap, 0, pBlock);
if (retval == 0)
{
errno = _get_errno_from_oserr(GetLastError());
}
}
and my source code / header files are:
main.cpp
#include <iostream>
#include <string>
#include "conio.h"
#include <crtdbg.h>
#include "Tax.h"
using namespace std;
int main()
{
string name;
double tax;
double income;
cout << "Enter your name: ";
cin >> name;
cout << "Enter your annually income: ";
cin >> income;
cout << "Enter your tax rate in pure numbers: ";
cin >> tax;
Tax Customer_1(name, income, tax);
cout << endl << "Customer name: " << Customer_1.getName() << endl <<
"Income annually: " << Customer_1.getIncome() << endl <<
"Tax percent(in real numbers): " << Customer_1.getTax() << endl <<
"Your income after tax, per month is: " << Customer_1.calculateTax() << endl;
cout << endl;
_getch();
return 0;
}
Tax.h:
#include <iostream>
#include <string>
using namespace std;
#ifndef TAX_H
#define TAX_H
class Tax
{
public:
//Default constructor
Tax();
//Overload constructor
Tax(string, double, double);
//destructor
~Tax();
//Accessor functions
string getName() const;
double getIncome() const;
double getTax() const;
//Mutator functions
void setName(string);
void setIncome(double);
void setTax(double);
double calculateTax() const;
private:
//Member variables
string newName;
double newIncome;
double newTax;
};
#endif
Tax.cpp
#include "Tax.h"
Tax::Tax()
{
newIncome = 0.0;
newTax = 0.0;
}
Tax::Tax(string name, double income, double tax)
{
newName = name;
newIncome = income;
newTax = tax;
}
Tax::~Tax()
{
}
string Tax::getName() const
{
return newName;
}
double Tax::getIncome() const
{
return newIncome;
}
double Tax::getTax() const
{
return newTax;
}
void Tax::setName(string name)
{
newName = name;
}
void Tax::setIncome(double income)
{
newIncome = income;
}
void Tax::setTax(double tax)
{
newTax = tax;
}
double Tax::calculateTax() const
{
return (( newIncome - ( newIncome * (newTax / 100))) / 12); // ((68400 - ( 68400 * (38/100 = 0.38))) / 12)
}
I've (slightly) modified your code to work out, try this:
tax.h:
#include <iostream>
#include <string>
#ifndef TAX_H
#define TAX_H
class Tax
{
public:
//Default constructor
Tax();
//Overload constructor
Tax(std::string, double, double);
//destructor
~Tax();
//Accessor functions
std::string getName() const;
double getIncome() const;
double getTax() const;
//Mutator functions
void setName(std::string);
void setIncome(double);
void setTax(double);
double calculateTax() const;
private:
//Member variables
std::string newName;
double newIncome;
double newTax;
};
#endif
tax.cpp:
#include "tax.h"
Tax::Tax()
{
newIncome = 0.0;
newTax = 0.0;
}
Tax::Tax(std::string name, double income, double tax)
{
newName = name;
newIncome = income;
newTax = tax;
}
Tax::~Tax() {}
std::string Tax::getName() const
{
return newName;
}
double Tax::getIncome() const
{
return newIncome;
}
double Tax::getTax() const
{
return newTax;
}
void Tax::setName(std::string name)
{
newName = name;
}
void Tax::setIncome(double income)
{
newIncome = income;
}
void Tax::setTax(double tax)
{
newTax = tax;
}
double Tax::calculateTax() const
{
return (( newIncome - ( newIncome * (newTax / 100))) / 12);
}
main.cpp
#include "tax.h" // <iostream> and <string> are here
// never put 'using namespace std' in a header file
using namespace std;
int main()
{
string name;
double tax;
double income;
cout << "Enter your name: ";
cin >> name;
cout << "Enter your annually income: ";
cin >> income;
cout << "Enter your tax rate in pure numbers: ";
cin >> tax;
Tax Customer_1(name, income, tax);
cout << endl << "Customer name: " << Customer_1.getName() << endl <<
"Income annually: " << Customer_1.getIncome() << endl <<
"Tax percent(in real numbers): " << Customer_1.getTax() << endl <<
"Your income after tax, per month is: " << Customer_1.calculateTax() << endl;
cout << endl;
return 0;
}
Take note of what has been replaced and the headers you were using; judging by the _getch() at the end of the code, I'm assuming you were using that so that your console window would not go away while debugging; if that was the case, you could instead do something with cin and the strings you already have like so:
...
cin.clear(); // clear buffer for erroneous 'enter' presses
cin >> name; // console will pause until you press enter
return 0;
Though if your intention was to actually have the console pause (vs. the program just ending), you might want to consider other (more elegant) solutions but that is beyond the scope of this question.
A couple of notes: the reason your program worked when not in debug mode (i.e. you went to 'release') is your inclusion of the <crtdbg.h> header; this file is only valid in a debug configuration and you really shouldn't include it if your not using anything in it (which you're not in your code). I also took out the using namespace std; in your tax.h file as there are numerous reasons not to include using namespace std in a header.
I hope that can help