My current assignment is to create a simple
Student Class that takes the
first name
last name
student ID number
from an object and outputs the name as a single string and his/her ID number. The program also has to count every student and output the total number of students. In this program I'm given 4 students.
I've created the program, given below. Everything compiles correctly and runs but my output is strange. Instead of giving me the students' ID and name, it gives me the number "-858993460". I have no idea why my program's doing this and a long search on the internet hasn't helped me much.
Student.h
#include <iostream>
#include <string>
using namespace std;
class Student
{
private:
string firstName;
string lastName;
int id;
string name;
public:
static int numberOfStudents;
Student();
Student(string theFirstName, string theLastName, int theID);
string getName();
int getID();
};
Student.cpp
#include "Student.h"
#include <iostream>
#include <string>
using namespace std;
//initialize numberOfStudents to 0
int Student::numberOfStudents = 0;
//initialize default constructor
Student::Student()
{
numberOfStudents++;
}
//initialize overloaded constructor
Student::Student(string theFirstName, string theLastName, int theID)
{
theFirstName = firstName;
theLastName = lastName;
theID = id;
numberOfStudents++;
}
//getName
string Student::getName()
{
return firstName += lastName;
}
//getID
int Student::getID()
{
return id;
}
main.cpp(this is my driver file)
#include "Student.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
Student st1("Hakan", "Haberdar", 1234), st2("Charu", "Hans", 2345), st3("Tarikul", "Islam", 5442), st4;
cout << "We created " << Student::numberOfStudents<<" student objects." << endl;
cout << st1.getID()<<" "<<st1.getName()<<endl;
cout << st2.getID()<<" "<<st2.getName()<<endl;
cout << st3.getID()<<" "<<st3.getName()<<endl;
cout << st4.getID()<<" "<<st3.getName()<<endl;
system("pause");
};
This is what my output is supposed to look like:
We created 4 student objects.
1234 Hakan Haberdar
2345 Charu Hans
5442 Tarikul Islam
0
This is what my output instead looks like:
We created 4 student objects.
-858993460
-858993460
-858993460
-858993460
I think my problem has something to do with my getName() function, but I'm not sure and I don't know what to try.
Student::Student(string theFirstName, string theLastName, int theID)
{
theFirstName = firstName;
theLastName = lastName;
theID = id;
numberOfStudents++;
}
Your assignments are the wrong way round. You're assigning the as yet uninitialised members to the arguments. Instead you should have:
Student::Student(string theFirstName, string theLastName, int theID)
{
firstName = theFirstName;
lastName = theLastName;
id = theID;
numberOfStudents++;
}
This mistake would have been avoided if you had used a member initialization list instead:
Student::Student(string theFirstName, string theLastName, int theID)
: firstName(theFirstName), lastName(theLastName), id(theID)
{
numberOfStudents++;
}
Not sure if the following is the reason for your issues, but it does seem wrong...
return firstName += lastName;
What this does is modifies firstname by appending last name to it, then returning modified string.
I think you meant to do something like
return firstName << ' ' << lastName;
Change your code to.
Student::Student(string theFirstName, string theLastName, int theID)
{
firstName = theFirstName;
lastName = theLastName;
id = theID;
numberOfStudents++;
}
Your code returning the value of id! which is not initialized.
So the code will return garbage.
Related
Hey Guys I could really use some help here. I am in a intro to C++ class, and have been trying my best to figure out this whole programming thing out. In one of my assignments i am getting an "undefined reference to" error in my program. It is coming up on line 30 of the main.cpp file. The line that creates a new student object called student1 using the constructor student. Any help figuring out the root of this problem would be greatly appreciated.
Thank you in advance!!
Student.h
#ifndef STUDENT_H_INCLUDED
#define STUDENT_H_INCLUDED
#include <string>
using namespace std;
class Student
{
private:
//instance variables declaration
// declare an int variable called studentID
int studentID;
// declare a string variable called firstName
// declare a string variable called lastName
string firstName;
string lastName;
// declare a string variable called major
string major;
// declare an int variable called gradePoints
int gradePoints;
// declare an int variable called totalCredits
int totalCredits;
public:
//member function declaration
Student(int , string , string , string , int , int );
//function getId() is the accessor for instance variable studentID
int getID();
//function getFullName() is the accessor for both firstName and lastName
//you will need to use string concatenation to return the student full name
string getFullName();
//function getMajor() is the accessor for instance variable major
string getMajor();
//function getGradepoints() is the accessor for instance variable gradePoints
int getGradepoints();
//function getCredits() is the accessor for instance variable totalCredits
int getCredits();
//function changeMajor(string ) is the mutator for instance variable major
//the function declaration is given as below
void changeMajor(string newMajor);
//function changeMajor(string, int, int) is an overloadded mutator for major
//the function declaration is given as below
void changeMajor(string newMajor, int newPoints, int newCredits);
//function toString() is used to print out all instance variables value
string toString();
};
#endif // STUDENT_H_INCLUDED
Student.cpp
#include "Student.h"
#include <iostream>
#include <sstream>
using namespace std;
Student::Student(int id, string fName, string lName, string major, int points, int credits)
{
studentID = id;
// write the segment of codes that assign input parameters to each of the instance variables
firstName=fName;
lastName=lName;
major=major;
gradePoints=points;
totalCredits=credits;
}
int Student::getId()
{
// write a line of code that returns the studentID
return studentID;
}
string Student::getFullName()
{
// write a line of code that returns the full name of the student, includes both first and last name.
stringstream ss;
ss<<firstName<<" "<<lastName;
return ss.str();
}
string Student::getMajor()
{
// write a line of code that returns the student's major
return major;
}
int Student::getGradepoints()
{
// write a line of code that returns the student grade points
return gradePoints;
}
int Student::getCredits()
{
// write a line of code that returns the student total credits
return totalCredits;
}
void Student::changeMajor(string newMajor)
{
// Change the value of the Student’s major variable to the new input’s value.
major=newMajor;
}
void Student::changeMajor(string newMajor, int newPoints, int newCredits)
{
// If newPoints and newCredits are less than or equal to their respective instance variable, update
// the student’s major variable to its new major. Otherwise, print an error message 'Invalid attempt'
major=newMajor;
gradepoints=newPoints;
totalCredits=newCredits;
}
string Student::toString()
{
stringstream ss;
ss<<"==================================="<<endl;
ss<<"Student ID :"<<getID()<<endl;
ss<<"Student Name :"<<getFullName()<<endl;
ss<<"Major :"<<getMajor()<<endl;
ss<<"Num. of Points :"<<getGradepoints()<<endl;
ss<<"Total Credits :"<<getCredits()<<endl;
return ss.str();
}
main.cpp
#include <iostream>
using namespace std;
#include "Student.h"
int main()
{
//declare variables where you will store inputs from user
int studentID;
string firstName;
string lastName;
string major;
int gradePoints;
int totalCredits;
//prompt the user for inputs studentID, firstName, lastName, major
//gradePoints and totalCredits.
//store the input in the declared variables
cout << "Enter student ID: ";
cin>>studentID;
cout << "Enter first name: ";
cin>>firstName;
cout << "Enter last name: ";
cin>>lastName;
cout << "Enter student major: ";
cin>>major;
cout << "Enter # of Points: ";
cin>>gradePoints;
cout << "Enter # of credits: ";
cin>>totalCredits;
//use the constructor with arguments to create a brand-new Student object
//called student1 using the variable values provided by the user
Student student1(studentID,firstName,lastName,major,gradePoints,totalCredits);
//call the getFullName() function to get the full name of the student.
cout << "\nStudent Name:\t" <<student1.getFullName()<<"\n";
//call the getId() method to get the ID of the student
cout <<"\nStudent ID:\t" << student1.getID() << "\n";
//call the toString() method to get every info. of the student
//show it on screen
cout << student1.toString() << endl;
//Attempt to change the major to 'International Affairs' with 10 points and 500 credits
//by calling changeMajor(String newMajor, int newPoints, int newCredits) function
//This should not succeed. It should print the 'Invalid attempt" message.
student1.changeMajor("International Affairs,10,500");
//call getMajor() method and store the student's old major
//into a variable oldMajor
string oldMajor =student1.getMajor();
//Change just the student’s major to
//'International Affairs' by calling changeMajor(String newMajor) function
student1.changeMajor("International Affairs");
// Print out the following message on screen
// <Student full name> has changed major from <Student_old_major> to <Student_new_major>
cout<<student1.getFullName()<<" has changed major from "<<oldMajor<<" to "<<student1.getMajor()<<endl;
//call toString() function to print student1 info. again on screen
cout<<student1.toString()<<endl;
}
I am using a GNU GCC Compiler to compile the program.
I think maybe here's the solution:
"This task tells g++ to take the active file (${file}), compile it, and create an executable file in the current directory (${fileDirname}) with the same name as the active file but without an extension (${fileBasenameNoExtension}), resulting in helloworld for our example."
I'm trying to set my values for my variables to be displayed in my output, but only one variable's value is managed to display in my output. Is it because there is some error in my get, set method in my class defining?
#include <iostream>;
#include <string>;
using namespace std;
class Employee
{
private:
string name;
int idNumber;
string department;
string position;
public:
void setEmployee(string nam, int id, string dep, string pos);
string getEmployee();
};
void Employee::setEmployee(string nam, int id, string dep, string pos)
{
name = nam;
idNumber = id;
department = dep;
position = pos;
}
string Employee::getEmployee()
{
return name, idNumber, department, position;
}
int main()
{
Employee emp;
cout << "Name \t" << "ID Number \t" << "Department \t" << "Position" << endl;
emp.setEmployee("Susan", 47899, "Accounting", "Vice President");
cout << emp.getEmployee();
return 0;
}
The error is here:
return name, idNumber, department, position;
In C++ a function can return only one single value.
Your getEmpoyee() function is defined to return one single string, and that is exactly what it does.
Using comma the way you do is a valid syntax so it compiles, but it does not do what you think. Everything after name is simply ignored.
The proper way is to create separate get functions for all fields.
It is also recommended to use separate set functions, each setting only one field.
If you want to initialize all fields at once, you should do it in the constructor.
Example:
class Employee
{
private:
string name;
int idNumber;
string department;
string position;
public:
//this is a constructor, it has no return type and same name as the class
Employee(string nam, int id, string dep, string pos);
string getEmployee();
};
Employee::Employee(string nam, int id, string dep, string pos)
{
name = nam;
idNumber = id;
department = dep;
position = pos;
}
int main() {
Employee emp("Susan", 47899, "Accounting", "Vice President");
}
This line
return name, idNumber, department, position;
Will return only name. If you want to return one string containing all values, you have to concatenate the values into one string, e.g. by using the + operator.
I recently started learning c++ so I'm still learning. Basically I'm trying to read my text file when the string "NEW_EMPLOYEE" is found and then store every line into their respective member variables until an empty line is found in the text file to stop. The problem I'm having is how can I use getline to import each line into each variable of my class "Employee" all at once? Should I use istringstream instead?
My text file called "employee.txt"
NEW_EMPLOYEE
460713
John
Smith
64000
36
END_OF_FILE
My class Employee:
class Employee {
private: //Member variables
int ID;
string FirstName;
string LastName;
int Salary;
int Hours;
public:
Employee() {} //Default constructor
Employee(int& id, string& firstName, string& lastName, int& salary, int& hours) {
ID = id;
FirstName = firstName;
LastName = lastName;
Salary = salary
Hours = hours;
}
};
My main.cpp:
#include <iostream>
#include <fstream>
int main() {
Employee employee;
int id;
string firstName;
string lastName;
int salary;
int hours;
string line;
ifstream employeeFile;
employeeFile.open("employee.txt");
while(getline(employeeFile, line)) {
if(line == "NEW_EMPLOYEE") {
do {
//Don't know what to do here???
} while (!line.empty());
}
}
employeeFile.close();
return 0;
}
The straightforward approach would be to do something like that
while(employeeFile >> line){
if(line != "NEW_EMPLOYEE") continue;
int id,salary,hours;
string firstName, lastName;
employeeFile >> id >> firstName >> lastName >> salary >> hours;
Employee employee = Employee(id, firstName, lastName, salary, hours);
// Do what you want with employee
}
This assumes that the data are written in the file always in the same order. I also assumed that the lines contain no spaces since they're either numbers or names so I used >> operator. You can use getline instead if that's not the case.
If you always sure the data are in the same order then this should be enough. If that's not true, I'd recommend writing the object as JSON in the file, and use a JSON parser library to read the file directly into an object.
yes..straight forward approach can help you otherwise u can use simple method like ...
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <sstream>
using namespace std;
int main() {
string x[100];
int i=0;
// Employee employee;
int id;
string firstName;
string lastName;
int salary;
int hours;
string line;
string text;
ifstream employeeFile;
employeeFile.open("employee.txt");
while(!employeeFile.eof())
{
getline(employeeFile,text);
x[i++]=text;
}
// employeeFile.close();
stringstream(x[1]) >> id; //string to int
firstName = x[2];
lastName = x[3];
stringstream(x[4]) >> salary;
stringstream(x[5]) >> hours;
//cout<<id<<" "<<firstName;
}
Then you can call your method . But straight forward approach is moore perfect than this :)
#include<iostream>
#include<string>
using namespace std;
/*this program takes a bank customer's info with the use of a class*/
//class definition
class BankCustomer
{
public:
BankCustomer(); //constructor for BankCustomer class
void fullname(string, string);
string firstname();
string lastname();
bool setsocial(int s); //accept a arg. of int type
int getsocial();
private:
string fname, lname, SSNlength; //can't be changed by client; sensitive info should be made private
};
//class implementation
BankCustomer::BankCustomer(){}
void BankCustomer::fullname(string f, string l)
{
fname=f;
lname=l;
}
string BankCustomer::firstname()
{
return fname;
}
string BankCustomer::lastname()
{
return lname;
}
bool BankCustomer::setsocial(int s)//function verifies that entered SSN is 9 digits long by counting # of digits of entered SSN
{
int count, SSNlength;
while(s != 0)
{
s /=10;
++count;
if(count == 9)
{
cout <<"\nValid SSN Entered!" << endl;
SSNlength=s;
return true;
}
}
}
int BankCustomer::getsocial()
{
return SSNlength;
}
//client program
int main()
{
BankCustomer customer; //customer declared as object of BankCust class
string firstname, lastname;
int ssn, s;
//data assignment
cout <<"\n Enter First Name\n" << endl;
cin >> firstname;
cout<<"\n Enter Last Name\n"<< endl;
cin >> lastname;
customer.fullname(firstname,lastname);
do
{
cout<<"\nEnter 9-Digit SSN"<< endl;
cin >> ssn;
customer.setsocial(ssn);
}
while(!customer.setsocial(ssn)); //function will repeat as long as entered user ssn forces setsocial() to evaluate it as false
//data ouput
cout <<"\nFirst Name: "<<customer.firstname()<<"\n"<< endl;
cout <<"\nLast Name: "<<customer.lastname()<<"\n"<< endl;
cout <<"\n SSN is: "<<customer.getsocial()<<"\n" << endl;
}
The error is targeting BankCustomer::getsocial(). The variable SSNlength is declared as an int type and getsocial() has a return type of int. I don't see anywhere in my code where I intend to convert SSNlength to a string. Is it how I'm passing and handling data with the setsocial() function?
That is wrong:
int BankCustomer::getsocial()
{
return SSNlength;
}
since SSNlength is a member variable of the class BankCustomer of type string, visible from BankCustomer::getsocial, even if not declared in the method. That how C++ works.
So the compiler complains that it cannot convert a string to an int (what you want to return).
this is where you declare it:
private:
string fname, lname, SSNlength; //can't be changed by client; sensitive info should be made private
Given the name of the variable, I suspect that you wanted to write:
private:
string fname, lname;
int SSNlength; //can't be changed by client; sensitive info should be made private
be careful, there's an auto variable called the same way in another method.
I suggest a naming rule for members to avoid all that. Example: prefix all members with m_:
private:
string m_fname, m_lname
int m_SSNlength; //can't be changed by client; sensitive info should be made private
In the code below I am trying to have the variable fullName be populated with whatever I enter during the operation of the function namecheck. I am not sure where I am going wrong. Please help and thank you for it.
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <cmath>
#include <string>
#include <fstream>
using namespace std;
string namecheck();
int main()
{
cout<<fixed;
string firstName;
string lastName;
string fullName;
char action;
int pin;
int pinTry =1;
int actionsTaken =0;
int joeyPin = 4433;
int mildredPin = 2849;
double joeyTotal = 3742.55;
double mildredTotal = 19.36;
double withdraw;
double deposit;
namecheck();
cout<<fullName;
}
string namecheck(){
string firstName;
string lastName;
string fullName;
string completeName;
double joeyTotal = 3742.55;
double mildredTotal = 19.36;
cout<<"Welcome to Blah National Bank!\n";
cout<<"What is your first name?\n";
cin>>firstName;
if (firstName == "END"){
cout<<"User totals: \n"
<<"Joey Stowy:\t"<<setprecision(2)<<joeyTotal<<endl<<endl
<<"Mildred Moredebt:\t"<<setprecision(2)<<mildredTotal<<endl<<endl;
}
if (firstName != "END"){
cout<<"What is your last name?\n";
cin>>lastName;
}
fullName = firstName+" "+lastName;
return fullName;
}
Change:
namecheck();
cout<<fullName;
to:
fullname = namecheck();
cout<<fullName()
.
When you call namecheck() in main, assign the result to fullName:
fullName = namecheck();