I'm fairly new to C++ and starting my main university project. All is going well so far, however I have came across this problem and after hours of searching the web i'm still clueless.
The problem occurs in Portfolio::displayAccounts()when I am trying to loop through a vector to display each element inside the vector.
It will not allow me to use the typical std::cout << which I have always used for things like arrays.
Any Help will be greatly appreciated.
#include <vector>
#include "Account.h"
class Portfolio
{
private:
std::vector<Account> accounts;
public:
double calculateNetWorth();
Portfolio();
void addAccount(std::string name, double balance);
void displayAccounts();
};
#include "Account.h"
double Account::getBalance() {
return balance;
}
Account::Account(std::string name, double balance){
this->name = name;
this->balance = balance;
}
#include <string>
class Account
{
private:
std::string name;
double balance;
public:
double getBalance();
Account(std::string name, double balance);
};
#include <iostream>
#include <string>
double Portfolio::calculateNetWorth() {
double total = 0;
for (auto& account : accounts) {
total += account.getBalance();
}
return total;
}
Portfolio::Portfolio() {
}
void Portfolio::addAccount(std::string name, double balance) {
std::cout << "Account Name: ";
std::cin >> name;
std::cout << "Account Balance: ";
std::cin >> balance;
Account account = Account(name, balance);
accounts.push_back(account);
}
void Portfolio::displayAccounts() {
std::cout << "nThe vector elements after push back are: ";
for (int i = 0; i < accounts.size(); i++) {
std::cout << accounts[i] << " ";
}
}
The standard library has no idea how an instance of your Account class should be outputted. In order to be able to write something like this:
std::cout << some_account;
you need to overload the << operator, for example like this:
class Account
{
private:
std::string name;
double balance;
public:
double getBalance();
Account(std::string name, double balance);
// add this so the overloaded << operator can access your private members
friend std::ostream& operator<<(std::ostream& os, const Account& o);
};
// Implementation
std::ostream& operator<<(std::ostream& os, const Account& a)
{
os << "Name: " << a.name << " Balance: " << a.balance << "\n";
return os;
}
Will print something like this for an Account instance:
Name: SomeName Balance: 123.45678
Bonus:
If you're using C++11 you can write this:
for (auto & account : accounts)
std::cout << account << " ";
instead of:
for (int i = 0; i < accounts.size(); i++) {
std::cout << accounts[i] << " ";
You're trying to print accounts[i] which has the Account type. As your object does not have a << overloaded operator, you won't be able to print anything.
There are 2 solutions :
Overload the << operator
Print rather the name or the balance attributes of your class
Related
My professor said operator overloading of << is optional here but I wanted to know how I could do it as I was only able to figure it out without using overloading.
This is a function in my code:
void listProducts()
{
//list all the available products.
cout << "Available products:\n";
for(int i=0; i<numProducts; i++)
cout << products[i]->getCode() << ": " << products[i]->getName() << " # "
<< products[i]->getPrice() << "/pound.\n";
}
And this is the product.cpp file:
Product :: Product(int code, string name, double price) {
this->code = code;
this->name = name;
this->price = price;
}
int Product:: getCode(){
return code;
}
string Product :: getName(){
return name;
}
double Product :: getPrice(){
return price;
}
You can do something like
std::ostream & operator<<(std::ostream &out,const classname &outval)
{
//output operation like out<<outval.code<<":"<<outval.name<<"#"<<outval.price;
return out;
}
and
friend std::ostream & operator<<(std::ostream &out,const classname &outval);
in your class to access private members.
If you understood the solution to your previous question this, then understanding the below code is very easy. The only difference is the usage of friend function about which you can read gfg link.
For your better understanding, the exact same example is given below,
#include <iostream>
using namespace std;
class Product
{
private:
int code; string name; double price;
public:
Product(int, string, double);
friend ostream & operator << (ostream &out, const Product &p);
};
Product :: Product(int code, string name, double price) {
this->code = code;
this->name = name;
this->price = price;
}
ostream & operator << (ostream &out, const Product &p)
{
out<< p.code << ": " << p.name << " # "
<< p.price << "/pound.\n";
return out;
}
int main()
{
Product book1(1256,"Into to programming", 256.50);
Product book2(1257,"Into to c++", 230.50);
cout<<book1<<endl<<book2;
return 0;
}
I am trying to add setter to my project as a requirement but am stuck on making it work. I commented out the areas I have to add it but everything I have looked up has not worked. I know I am close but everything seems to not work.
#include "pch.h"
#include <string>
#include <conio.h>
#include <iostream>
using namespace std;
template <class T>
class Holder
{
private:
T thing;
int number; //add an integer data member that stores the number of data members of whatever class is stored in "thing"
public:
void standardInput();
void standardOutput();
void setNumber(int); // declare a setter function for the new data member
};
template <class T>
void Holder<T>::standardInput()
{
cout << endl;
cout << "You will be asked to enter " << n.setNumber << " items" << endl; // a line of output that use the data member with the number
cin >> Holder<T>::thing;
}
template <class T>
void Holder<T>::standardOutput()
{
cout << endl;
cout << "Here's the data you requested: " << endl;
cout << Holder<T>::thing << endl;
}
template<class T>
void Holder<T>::setNumber(int n) //implement the setter function for the new data member
{
setNumber = n;
}
// This is the first of two custom classes
class Student
{
friend ostream& operator<<(ostream&, Student&);
friend istream& operator>>(istream&, Student&);
private:
string name;
double tuiton;
};
ostream& operator<<(ostream& out, Student& a)
{
out << "The Student " << a.name << " Tuiton is: " << a.tuiton << endl;
return out;
}
istream& operator>>(istream& in, Student& a)
{
cout << "Enter the name of student: ";
in >> a.name;
cout << "What is the Price of tuiton? ";
in >> a.tuiton;
return in;
}
// This is the second of two custom classes
class FastFood
{
friend ostream& operator<<(ostream&, FastFood&);
friend istream& operator>>(istream&, FastFood&);
private:
int valueNumber;
double cost;
};
ostream& operator<<(ostream& out, FastFood& a)
{
out << " The Combo Number is " << a.valueNumber << " .It costs " << a.cost << endl;
return out;
}
istream& operator>>(istream& in, FastFood& a)
{
cout << "What is the Combo number? ";
in >> a.valueNumber;
cout << "Enter cost: ";
in >> a.cost;
return in;
}
int main()
{
cout << "For an integer: " << endl;
Holder<int> val;
// use the setter to store 1.
val.standardInput();
val.standardOutput();
cout << "For a Student:" << endl;
Holder<Student> aCollegeStudent;
// use the setter to store 2.
aCollegeStudent.standardInput();
aCollegeStudent.standardOutput();
Holder<FastFood> vMeal;
// use the setter to store 3.
vMeal.standardInput();
vMeal.standardOutput();
cout << endl;
system("pause");
return 0;
}
This is supposed to ask the integer along with the student and fastfood information. I required to add a setter in the template but wont need to use a getter due to standard input and output just cant figure out the right way to do it.
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;
}
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);
I have a question regarding a homework assignment.
I have two classes. One is called ticket.cpp, and the other is called TicketOrder.cpp
The main is within the ticket.cpp.
I am using a g++ compiler on Linux.
What I'm doing is trying to is print out a vector of a TicketOrder object called orders, but it gives me the following error:
ticket.cpp:57: error: no match for 'operator<<' in 'std::cout << orders. std::vector<_Tp, _Alloc>::operator[] with _Tp = TicketOrder, _Alloc = std::allocator'
Here is my code:
ticket.cpp
#include <iostream>
#include <vector>
#include <limits>
#include <cctype>
#include "TicketOrder.cpp"
using namespace std;
int main ()
{
int numberoftickets=0;
string input2;
char input3;
int profit=0;
vector <TicketOrder> orders;
int atotalmoney=0;
int btotalmoney=0;
int ctotalmoney=0;
int dtotalmoney=0;
int etotalmoney=0;
do
{
cout << "\nPick a ticket that you would like to buy: \n\n";
cout << "(A) Students without an activity card: $2.00 \n";
cout << "(B) Faculty and staff: $3.00 \n";
cout << "(C) USC alumni: $5.00 \n";
cout << "(D) UCLA students and alumni: $20.00 \n";
cout << "(E) Everyone else: $10.00 \n";
cin >> input3;
if (input3=='A')
{
cout << "How many tickets do you wish to buy? " <<endl;
if (numberoftickets >0)
{
TicketOrder order;
order.setQuantity(numberoftickets);
order.setType(input3);
orders.push_back(order);
for (int i=0; i< orders.size(); i++)
{
cout << orders[i];
}
}
}
else
{
cout << "Sorry did not recognize input, try again. " << endl;
}
} while (input3 != 'S');
TicketOrder.cpp:
#include <iostream>
using namespace std;
class TicketOrder
{
public :
//Getters
int getQuantity() const
{
return quantity;
}
char getType() const
{
return type;
}
//Setters
void setQuantity (int x)
{
quantity=x;
}
void setType(char y)
{
type =y;
}
private:
char type;
char quantity;
};
As the compiler is clumsily trying to explain, the code is missing an operator<< for the TicketOrder class.
class TicketOrder {
public:
friend std::ostream& operator<<(std::ostream& os, TicketOrder const& order) {
os << "Type: " << type << ", quantity: " << quantity;
return os;
}
char type;
int quantity;
};
(Note: you probably want to change quantity to int.)
You must add the operator << function as a friend to be able to print values from your TicketOrder objects with cout. Further reading
You're attempting to use the << operator on cout and a TicketOrder object. That is undefined. You should use the TicketOrder object to generate a string first, then output that via cout. Either that, or you can define the << operator for the TicketOrder class, as described in one of the other two answers.