vector issue, C++ not sure what i've done wrong - c++

Ok so i'm fairly new to c++ and this is my first try using vectors. My goal is to store objects into a vector. I'm trying to follow this youtube tutorial:
http://www.youtube.com/watch?v=iPlW5tSUOUM
and i think mine is pretty much the same apart from his runs.
I just keep getting errors and it won't run. Any help would be appreciated :)
Maybe it's something small, but i've been checking for a while now and i can't see anything.
Errors:
1>c:\users\user\desktop\vector objects c++\testvectorobjects\testvectorobjects\main.cpp(61): error C3867: 'Employees::getSalary': function call missing argument list; use '&Employees::getSalary' to create a pointer to member
1>c:\users\user\desktop\vector objects c++\testvectorobjects\testvectorobjects\main.cpp(61): error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'overloaded-function' (or there is no acceptable conversion)
1>c:\program files (x86)\microsoft visual studio 11.0\vc\include\ostream(695): could be 'std::basic_ostream<_Elem,_Traits> &std::operator <<>(std::basic_ostream<_Elem,_Traits> &,const char *)'
I have 3 files: main.cpp, Employee.h, Employees.cpp
//main.cpp
#include <iostream>
#include <string>
#include <vector>
#include "Employee.h"
void fillVector(vector<Employees>&);
//fill vector - fills in Employee Info
//vector<Employees>& - Employees at the station
void printVector(const vector<Employees>&);
//print vector - prints the employee info
//const vector<Employees>& - employees at the station
using namespace std;
vector<Employees> Staff;
int main(){
fillVector(Staff);
printVector(Staff);
}
//filling the employee vector
void fillVector(vector<Employees> & newStaff){
int id;
double salary;
string name;
cout << "Number of Employees" << endl;
int amountEmployees;
cin >> amountEmployees;
for (int i = 0; i < amountEmployees; i++) {
cout << "Enter Employee Id: ";
cin >> id;
cout << "Enter Employee Salary: ";
cin >> salary;
cout << "Enter Employee Name: ";
cin >> name;
Employees newEmployees(id, salary, name);
newStaff.push_back(newEmployees);
cout << endl;
}
cout << endl;
}
//printing the employee vector
void printVector(const vector<Employees>& newStaff){
unsigned int size = newStaff.size();
for (unsigned int i = 0; i < size; i++) {
cout << "Employee Id: " << newStaff[i].getID << endl;
cout << "Employee Name: " << newStaff[i].getName << end;
cout << "Employee Salary: " << newStaff[i].getSalary << end;
cout << endl;
}
}
//Employee.h
//Header
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <iostream>
#include <string>
using namespace std;
class Employees{
public:
//after
//Default Constructor
Employees();
//Overload constructor
Employees(int, double, string);
//Destructor
~Employees();
//Accessor Functions
int getID() const;
//getId
//return int - Id for Employee
double getSalary() const;
//getSalary
//return salary - salary of Employee
string getName() const;
//getName
//return name - Name of Employee
//Mutators
void setId(int);
//setId - for Employee
void setSalary(double);
//setSalary - for Employee
void setName(string);
//setName - for Employee
//
//before
//ID
//void setEmployeeId(int a){
//employeeId = a;
//}
////Salary
//void setSalary(double b){
//salary = b;
//}
////Name
//void setName(string c){
//name = c;
//}
private:
//after
//before
int employeeId; //id
double employeeSalary; //salary
string employeeName; //name
};
#endif
//Employees.cpp
#include "Employee.h"
Employees::Employees() {
employeeName = ' ';
}
Employees::Employees(int id, double salary, string name){
employeeId = id;
employeeSalary = salary;
employeeName = name;
}
Employees::~Employees(){
}
int Employees::getID()const{
return employeeId;
}
double Employees::getSalary()const{
return employeeSalary;
}
string Employees::getName()const{
return employeeName;
}
void Employees::setId(int id){
employeeId = id;
}
void Employees::setSalary(double salary){
employeeSalary = salary;
}
void Employees::setName(string name){
employeeName = name;
}

'Employees::getSalary': function call missing argument list;
That seems quite clear: getSalary is a function, and you need an argument list when you call a function:
cout << "Employee Salary: " << newStaff[i].getSalary() << endl;
^^ ^
and similarly for the calls to getID and getName.
Fixing that should also fix the second error; or that might be caused by the mistyping of endl.

I think the error is pretty self explaining, once you know a bit of C++ terms. The second part (use '&Employees::getSalary' to create a pointer to member) will actually confuse you, because the compiler it talking about a totally unrelated C++ capability, that it thinks you may be trying to use.
Let's see:
'Employees::getSalary': function call missing argument list
To call a function, you have to specify the argument list, with parenthesis, even if you have no arguments at all!
cout << "Employee Salary: " << newStaff[i].getSalary() << end;
That is, add a few () here and there.

You have to use function call operator () (application operator) to call a function
function_name() // call a function named function_name
thus:
cout << "Employee Id: " << newStaff[i].getID() << endl;
^^
cout << "Employee Name: " << newStaff[i].getName() << end;
^^
cout << "Employee Salary: " << newStaff[i].getSalary() << end;
^^

This:
newStaff[i].getName
Needs to be this:
newStaff[i].getName()
And so on.

Related

Trying to sort Vector of Objects

As the title suggest, I am trying to sort a vector of objects by the GPA. My main issue is putting a method where I define the function for my comparison. The vector itself holds objects of five fields, which includes: string name, string ssn, string year, float credit, float gpa. I know theirs a way to use the sort operator. I am new to C++ so I am not very knowledgeable in this language. I appreciate the help! Here is the code:
#include <iostream>
#include <string>
#include <iterator>
#include <iomanip>
#include <fstream>
#include <vector>
#include <sstream>
#include <algorithm>
#include <cstdlib>
#include <list>
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.
float gpa; //Most up to date gpa for the student
float 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 = (float)atof(sGPA.c_str());
credits = (float)atof(sCredits.c_str());
}
string getName() {
return name;
}
string getSSN() {
return ssn;
}
float getGPA() {
return gpa;
}
float 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;
list<Undergrad> myList;
list<Undergrad>::iterator i;
//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);
myList.push_back(g);
}
ip.close();
//This deletes the last object in the list and stores it in a temp object. It assigns that object to the beginning of the list.
Undergrad temp = myList.back();
myList.pop_back();
myList.insert(myList.begin(), temp);
/* for (int i = 0; i < myList.size(); i++) {
cout << "Name: " << myList[i].getName() << endl;
cout << "SSN: " << myList[i].getSSN() << endl;
cout << "Year: " << file[i].get_year() << endl;
cout << "Credit: " << file[i].getCredit() << endl;
cout << "GPA " << file[i].getGPA() << endl;
cout << " " << endl;
}
*/
/*for (Undergrad &x : myList) { //Goes through my list and displays its contents
x.print(); //This isn't bringing up errors.
}
*/
//This code copy the contents of the list to a vector.
std::vector<Undergrad> vect{ std::make_move_iterator(std::begin(myList)),
std::make_move_iterator(std::end(myList)) };
std::sort(vect.begin(), vect.end(), CompareGPA);
for (Undergrad &x : vect) {
x.print();
}
system("pause");
return 0;
}
Furthermore this is the code Im trying to implement to get the comparision
bool CompareGPA(const Student& left, const Student& right) {
return left.gpa > right.gpa;
}
Using lambda you can implement like this:Use a property int get_gpa() const to access the protected member.
std::sort(vect.begin(), vect.end(), [] (const Student& left, const Student& right)
{
return left.get_gpa() > right.get_gpa();
});
Here how to implement the property ( a member function to return the protected variable) :
int get_gpa() const
{
return gpa;
}

error access violation writing location 0x00229C20. when trying to input a string in console

i am trying to input a string in my code in c++ and when i run i always get the following error: Exception thrown at 0x0F5023F5 (msvcp140d.dll) in assignment-1.exe: 0xC0000005: Access violation writing location 0x00229C20. i will post my code below if anyone could help me that would be great.Please note that i already know that its a problem with me trying to access the memory location on which you dont have access to, i just dont know how to fix it.
HEADER FILE:
#ifndef item_H
#define item_h
class item
{
private:
//attributes
int itemID;
char itemName[20];
float itemcost;
float itemprice;
//utility function
float calcPrice();
public:
//constructor
item(int = 000, char[] = "itemUnknown", float = 0,float = 0);
//destructor
~item();
//set functions
void setAll(int, char[], float, float);
void setID(int);
void setName(char[]);
void setCost(float);
//get function
int getID();
float getcost();
float getprice();
void getname();
//print function
void print();
};
#endif
CPP:
#include "Dariush.h"
#include <iostream>
#include <iomanip>
#include<string>
using namespace std;
//constructor will set attributes
item::item(int ID, char n[] , float c,float p)
{
setID(ID);
setName(n);
setCost(c);
setAll(ID, n, c, p);
}
//destructor will print destroing two objects
item::~item()
{
cout << "destroing two objects : " << " " << itemName << " "
<< " & " << itemName << endl;
}
//set functions :
void item::setID(int ID)
{
cout << "please enter the item's ID : " << endl;
cin >> ID;
}
void item::setName(char n[])
{
cout << "please enter the item's name" << endl;
cin.ignore();
cin.getline(n, 20);
}
void item::setCost(float c)
{
cout << "please enter the item's cost : " << endl;
cin >> c;
}
void item::setAll(int ID, char n[], float c, float p)
{
itemID = (ID > 0 && ID < 999) ? ID : 0;
strcpy_s(itemName, n);
itemcost = (c > 0) ? c : 0;
calcPrice();
}
//get functions :
int item::getID()
{
return itemID;
}
float item::getcost()
{
return itemcost;
}
float item::getprice()
{
return itemprice;
}
void item::getname()
{
cout << itemName << endl;
}
//print function :
void item::print()
{
cout << "ID : " << itemID << endl
<< "Name : " << itemName << endl
<< "cost : " << itemcost << endl
<< "price : " << itemprice << endl;
}
// utility function for price callculation :
float item::calcPrice()
{
if (itemcost < 1000)
{
itemprice = itemcost + (itemcost*0.1);
}
else
itemprice = itemcost + (itemcost*0.2);
return itemprice;
}
MAIN.CPP:
#include "Dariush.h"
#include <iostream>
#include<string>
using namespace std ;
void main()
{
item i1;
item i2;
i1.print();
i2.print();
}
thanks for the assistance.
Lets take a closer look at these three function declarations:
item(int = 000, char[] = "itemUnknown", float = 0,float = 0);
void setAll(int, char[], float, float);
void setName(char[]);
The thing here is that the character "array" arguments you declare are not really arrays at all. Instead they are pointers. When declaring arguments, e.g. char n[] is actually translated by the compiler as char *n.
The constructor declaration makes the pointer point to the constant string literal "". And the important thing about constant string literals is that they are indeed constant. Trying to modify a string literal leads to undefined behavior. And change this literal is what you are trying to do with the cin.getline(n, 20) call in the setName function. Not only that, but you are also telling the cin.getline function to read more than fits in the string literal.
The simple solution is to have setName read into the member variable itemName instead.
There are many problems with this code, but the one that is causing the access violation is:
void item::setName(char n[])
{
cout << "please enter the item's name" << endl;
cin.ignore();
cin.getline(n, 20); //here
}
You should use cin.getline(itemName, 20); instead.
Also, to prevent such error in the future, declare arguments as char const n[] instead of char n[] - good compiler should display a warning when you use string literals with non-const pointer as argument.

Can anyone help me how to call this function parameter from class to be displayed in my output

This coding where I used function overloading is a code where user have to input their pointer for 4 subjects and its credit hour so it prints out their GPA. The thing is I have 3 parameter in Student(string test123, string nama, string vinto ). But I only want to display either one of the string. Lets say I want the Vinto to be print out. How can I call the vinto in my Display function so that it prints out Vinto. Heres's My coding.
CPP.cpp
#include <iostream>
#include "student.h"
using namespace std;
void main(void)
{
string nama;
string test123;
int i;
Student StudentA(test123, nama, "vinto");
cout << "key in points for 4 subject\n";
StudentA.Getpointers();
StudentA.Display(test123);
}
Student.h
#include<iostream>
#include<string>
using namespace std;
class Student
{
public:
Student(string test123, string nama, string vinto );
void Getpointers();
void Display(string name);
private:
double points[4];
int creditHours[4];
string name;
double CalculateGPA();
};
Student.cpp
#include <iostream>
#include <iomanip>
#include<string>
#include "student.h"
using namespace std;
Student::Student(string test123, string nama, string vinto)
{
name = nama;
}
void Student::Getpointers()
{
for (int i = 0; i<4; i++)
{
cout << "points for subject :" << i + 1 << endl;
cin >> points[i];
cout << "credit hour for subject " << i + 1 << endl;
cin >> creditHours[i];
}
}
void Student::Display(string name)
{
cout << "Hello " << name << endl;
cout << "Your current GPA is " << setprecision(3) << CalculateGPA() << endl;
}
double Student::CalculateGPA()
{
double totalpoints = 0;
int totalcreditHours = 0;
for (int i = 0; i<4; i++)
{
totalpoints += (points[i] * creditHours[i]);
totalcreditHours += creditHours[i];
}
return totalpoints / totalcreditHours;
}
Well, the vinto argument of your constructor is not saved anywhere, so in this example you cannot get it back. However, you could store it:
First, add a vinto field to the class:
class Student
{
public:
Student(string test123, string nama, string vinto );
void Getpointers();
void Display(string name);
private:
double points[4];
int creditHours[4];
string name;
string vinto;
double CalculateGPA();
};
Then, store the vinto argument value in this field:
Student::Student(string test123, string nama, string vinto)
{
name = nama;
this->vinto = vinto;
}
After this, you may use vinto:
void Student::Display(string name)
{
cout << "Hello " << name << endl;
cout << "Your current GPA is " << setprecision(3) << CalculateGPA() << endl;
cout << "Your vinto is " << vinto << endl;
}
Also, it's a bit strange that you store student's name in the object field, but use another name (which is passed to Student::Display) to say Hello to him.

C++ Error (operand types are 'std::string and 'void')

1st of all Im newBee at C++ programming.so please apologize if i make lots of mistake while asking questions.
My problem is:
i create class which contain private variable and Methods like below:
class Records{
private:
string name;
public:
string n;
void setValue(){
cout << "Enter name" << endl;
cin >> name;
}
void getValue(){
n = name;
cout << "Name is: " << n << endl;
}
};
I have run your code on GCC compiler, it's successfully worked. Please, see complete example :
#include <iostream>
using namespace std;
class Records{
private:
string name;
public:
string n;
void setValue(){
cout << "Enter name" << endl;
cin >> name;
}
void getValue(){
n = name;
cout << "Name is: " << n << endl;
}
};
int main()
{
Records r;
r.setValue();
r.getValue();
}

My output is not correct when displayed

My output name is not being displayed in my program. I have been looking at the code and
I just can't find my error
input
name : John Dough
id : 123445
start date : 10312014
shift: 2
output
name : ^^^^^^ <<<< I am having problem my name not being displayed
id : 123445
start date : 10312014
shift : 2
code
//This program demostrates a class and a derived class with constructors.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Employee
{
private:
char EmpName;
int EmpNum;
int HireDate;
public:
void setEmpName(char);
void setEmpNum(int);
void setHireDate(int);
char getEmpName() const;
int getEmpNum() const;
int getHireDate() const;
Employee();
};
void Employee::setEmpName(char x)
{
EmpName = x;
}
void Employee::setEmpNum(int y)
{
EmpNum = y;
}
void Employee::setHireDate(int z)
{
HireDate = z;
}
char Employee::getEmpName() const
{
return EmpName;
}
int Employee::getEmpNum() const
{
return EmpNum;
}
int Employee::getHireDate() const
{
return HireDate;
}
Employee::Employee()
{
cout << "I will ask you some questions about an employee.\n\n";
}
class ProductionWorker : public Employee
{
private:
int Shift;
double HourlyPayRate;
public:
void setShift(int);
void setHourlyPayRate(double);
int getShift() const;
double getHourlyPayRate() const;
ProductionWorker();
};
void ProductionWorker::setShift(int a)
{
Shift = a;
}
void ProductionWorker::setHourlyPayRate(double b)
{
HourlyPayRate = b;
}
int ProductionWorker::getShift() const
{
return Shift;
}
double ProductionWorker::getHourlyPayRate() const
{
return HourlyPayRate;
}
ProductionWorker::ProductionWorker()
{
cout << "After answering the questions,\n";
cout << "I will display the employee's information.\n\n\n";
}
int main()
{
ProductionWorker info;
char name[100];
int num;
int date;
int shift;
double rate;
cout << "What is the employee's name? ";
cin.getline(name, 100);
cout << "What is the employee's number? ";
cin >> num;
cout << "What is the employee's hire date?\n";
cout << "(Month, day, and year without any slashes,\n";
cout << "dashes, commas, or other punctuation.)\n";
cout << "For example, January 14, 1983 would look like 01141983. ";
cin >> date;
cout << "Does the employee work shift 1 or shift 2? ";
cin >> shift;
cout << "How much does the employee make per hour? ";
cin >> rate;
info.setEmpName(name[100]);
info.setEmpNum(num);
info.setHireDate(date);
info.setShift(shift);
info.setHourlyPayRate(rate);
cout << "\n\nHere is the employee's data:\n\n";
cout << "Employee's Name: " << info.getEmpName() << endl;
cout << "Employee's Number: " << info.getEmpNum() << endl;
cout << "Employee's Hire Date: " << info.getHireDate() << endl;
cout << "Employee's Shift: " << info.getShift() << endl;
cout << setprecision(2) << fixed;
cout << "Employee's Hourly Pay Rate: $" << info.getHourlyPayRate() << endl << endl;
return 0;
}
This is wrong: you're accessing an out-of-range character instead of passing the array to the function
char name[100];
//.. initialize name..
info.setEmpName(name[100]); // Accesses the 100th character (out-of-range [0-99])
void Employee::setEmpName(char x)
{
EmpName = x;
}
I would go for using std::string by changing EmpName (also wrong, it's not a single character) to a std::string
class Employee
{
private:
string EmpName;
int EmpNum;
int HireDate;
public:
void setEmpName(std::string& name);
void setEmpNum(int);
void setHireDate(int);
string getEmpName() const;
int getEmpNum() const;
int getHireDate() const;
Employee();
};
Also don't forget to change char name[100] to a std::string in the main function.
Live Example
You can of course accomplish this also with char arrays, in that case if you intend to use a fixed-size array you could either pass it by reference or just copy the content of a pointer to the array into a memory array for Employee.
There are multiple problems with your code.
First, the data type of Employee::EmpName should not be char. It should be a char array or even better would be a std::string.
Second the parameter of the setEmpName function should be either a const char* or a const std::string&.
Third, the name variable should perhaps be a std::string instead of a char array. Of course if you make that change the parameter of the setEmpName function should be const std::string&.
Fourth, when calling the setEmpName function you should just call it as follows: info.setEmpName(name).
Next, you should use std::getline(cin, name) instead of cin.getline(name, 100).
I'm first correcting your mistakes and then giving you a better alternative solution.
The member of your class and the setter function's parameter are only a single char. Change them to arrays:
char EmpName[100];
and
void setEmpName(char[]);
and in the implementation, you need to copy the content of the given array to your member:
void Employee::setEmpName(char[] x) {
memcpy(EmpName, x, 100);
}
However, this is the C way to do this.
The C++ way to do this is to use std::string. For this, change the types of the member, the parameters in the setter and in the getter as well as the type in main to std::string. To read a std::string, use the free-standing overload of getline which only takes the stream and the string (but no count):
getline(cin, name);