I am working on this for an assignment and cannot figure out how to even get started to write the function for the following program.
The code given is:
#include <iostream>
#include <string>
#include "BACCOUNT.H"
using namespace std;
void display(const bankAccount & anAcct)
{
}
int main()
{
bankAccount a("Annie Hill", 123.00);
bankAccount b("Becker" , 45.60);
display(a);
display(b);
return 0;
}
and I need to write a display function that will make the name and balance for bankAccount a and bankAccount b display.
I've been working on this for about 3 days now, and cannot figure out how to even start.
my output needs to be:
bankAccount: Hill, Annie, $123.00
bankAccount: Becker, Bob, $45.00
what I've got so far is;
anAcct.name();
string name = anAcct.name();
int space = name.find("5");
name.substr(0, 5);
name.substr(5, 9);
name.length();
cout << name;
Which I know is way off, I've just been trying trial and error.
You can overload << operator in your bankAccount class and let that operator print the content of your class from display function.
e.g. code for reference
friend std::ostream& operator<<(std::ostream& os, bankAccount& a)
{
os << a.name() << ":" << a.accountBalance();
}
void display(const bankAccount & anAcct)
{
std::cout << anAcct;
}
bankAccount is you class and you should have at leat 2 variables in it !. is the name and second will be the amount and you need a diolay() function that display those variable using getters
void bankAccount::display(){
std::cout << this->getname() <<this->getamount<< "$ "<< std::endl;
}
in the main function using a.display() and there you go
Related
I am trying to make a priority queue with Student class.
I overloaded operator< function which compare student id of two objects of Student class, but my code does not work.
Could you give me any advice?
#include <iostream>
#include <queue>
#include <vector>
#include <string>
using namespace std;
class Student {
public:
string name;
int id;
Student(string str, int n) {
this->name = str;
this->id = n;
};
};
bool operator<(const Student& a, const Student& b) {
return a.id < b.id;
}
int main() {
priority_queue<Student> pq;
pq.push(Student("Miria", 1));
pq.push(Student("Ken", 2));
pq.push(Student("Bob", 3));
while (!pq.empty()) {
cout << pq.top() << endl;
pq.pop();
}
return 0;
}
I am kind of unaware what an "My code does not work seems", although it seems to me that you are not printing the objects in the priority_queue correctly.
The appropriate way of printing them will be by using the object's properties or using a string representation operator overload. Let me give you an example of how the simpler version of the code would look like by using your code:
cout << pq.top().name << "'s id is: " << pq.top().id << endl;
The reason your code is not working is because you are lacking the output operator overload. You are not able to compile the program itself if you are lacking this operator.
The former spoken of is done the foreshown code down below:
friend ostream& operator<<(std::ostream& output, const Student& obj) {
return output << obj.name << "'s id is: " << obj.id << endl;
};
This way you will be able to use the pq.top() function in the cout stream:
cout << pq.top();
I hope this is what you expect and if you want to make it in increase order like Java you can use priority_queue.
The expected output as the question is described should be:
Bob's id is: 3
Ken's id is: 2
Miria's id is: 1
When I am executing this, a garbage value is coming with account balance info. Can anyone help me why?
#include<bits/stdc++.h>
using namespace std;
class Bankaccount
{
public:
int accnumber,accbalance;
int display()
{
cout<<"Account number is: "<<accnumber;
cout<<"\nAccount balance is: "<<accbalance;
}
};
int main() {
Bankaccount a;
Bankaccount b;
a.accnumber = 123456;
a.accbalance =50;
b.accnumber = 67890;
b.accbalance = 2000;
cout<<"Account details of A\n\n"<<a.display()<<endl;
cout<<"\nAccount details of B\n\n"<<b.display();
return 0;
}
The function display() should return void in this case. Your version has in its signature that it returns int, but then you don't return anything. This leads to undefined behavior.
Also it is bad practice to use using namespace std and #include<bits/stdc++.h>.
Read up here Why is "using namespace std;" considered bad practice?
And here How does #include <bits/stdc++.h> work in C++?
#include <iostream>
class Bankaccount
{
public:
int accnumber, accbalance;
void display()
{
std::cout << "Account number is: " << accnumber << "\n";
std::cout << "Account balance is: " << accbalance << "\n";
}
};
int main()
{
Bankaccount a;
Bankaccount b;
a.accnumber = 123456;
a.accbalance =50;
b.accnumber = 67890;
b.accbalance = 2000;
std::cout<<"Account details of A\n\n";
a.display(); // this is how to use display
std::cout<<"\nAccount details of B\n\n";
b.display();
return 0;
}
You are inserting to std::cout, among others, result returned from function display
which should be int, but, considering that your function has no return statement everything is possible, basically you are sending undefined value to ostream cout, and that is what garbage is by definition.
Most probably this is what you wanted to achieve:
https://wandbox.org/permlink/bpPth9WutHaiU5jQ
#include <bits/stdc++.h>
using namespace std;
class Bankaccount {
public:
int accnumber, accbalance;
std::ostream& display(std::ostream& out) const
{
out << "Account number is: " << accnumber;
return out << "\nAccount balance is: " << accbalance;
}
};
std::ostream& operator<<(std::ostream& out, const Bankaccount& acc)
{
return acc.display(out);
}
int main()
{
Bankaccount a;
Bankaccount b;
a.accnumber = 123456;
a.accbalance = 50;
b.accnumber = 67890;
b.accbalance = 2000;
cout << "Account details of A\n" << a << endl;
cout << "\nAccount details of B\n" << b << endl;
return 0;
}
Your int display() function doesn't return an int so you'll have undefined behaviour after that function has been called. If it had returned an int, that number had been printed, but I suspect that's not what you wanted.
The garbage you see is an int picked from the stack (because display() was supposed to put an int there). It was put the for a reason by some other function, but now it's gone, so anything can happen. To avoid this, you could declare your function void display() - but then you wouldn't be able to stream it, which is what it looks like you want to do.
If you want to be able to stream your objects, you need to define streaming operators to do the job. I've replaced your display() function with an out stream operator (operator<<) here:
#include <iostream>
//#include<bits/stdc++.h> // non-portable, don't use it
// using namespace std; // brings in too much in the namespace
using std::cout; // prefer this or just write std::cout everywhere
class Bankaccount {
public:
int accnumber, accbalance;
friend std::ostream& operator<<(std::ostream& os, const Bankaccount& ba) {
return os << "Account number is : " << ba.accnumber
<< "\nAccount balance is: " << ba.accbalance << "\n";
}
};
int main() {
Bankaccount a;
Bankaccount b;
a.accnumber = 123456;
a.accbalance = 50;
b.accnumber = 67890;
b.accbalance = 2000;
// std::endl is approx. the same as "\n" + std::flush. You don't need flushing.
cout << "Account details of A\n\n" << a << "\n";
cout << "\nAccount details of B\n\n" << b << "\n";
}
I am learning about functions and classes, and wrote my own code. I used the constructor to just initialize the variables. I have a function that is supposed to get the info I initialized with the constructor and allow me to display it. However, it doesn't want to work. I am not really sure what I am doing wrong. My error code says that I have unresolved externals because of my "void" function. I thought my function was not returning anything but rather just displaying the input it got from the initialization of the constructor.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class Berries {
string Nameofberries;
int Price;
public:
Berries (string N,int B)
{
Nameofberries = N;
Price = B;
}
void GetBerryInfo(const Berries& B)
{
cout << B.Nameofberries << endl;
cout << B.Price << endl;
}
};
void GetBerryInfo (const Berries& B);
int main ()
{
Berries Berryinfo1( "Raspberries", 7);
cout << GetBerryInfo;
system("pause");
return 0;
}
There are several mistakes.
void GetBerryInfo(const Berries& B)
{
cout << B.Nameofberries << endl;
cout << B.Price << endl;
}
should be
void GetBerryInfo()
{
cout << Nameofberries << endl;
cout << Price << endl;
}
==================================================================
void GetBerryInfo (const Berries& B);
should be removed.
==================================================================
cout << GetBerryInfo;
should be
Berryinfo1.GetBerryInfo();
==================================================================
All computer langauges are fussy, you have to get the details right, as well as understand the concepts.
This will do what you wanted:
# include <iostream>
# include <iomanip>
# include <string>
using namespace std;
class Berries {
string Nameofberries;
int Price;
public:
Berries (string N,int B)
{
Nameofberries = N;
Price = B;
}
void GetBerryInfo()
{
cout << Nameofberries << endl;
cout << Price << endl;
}
};
int main ()
{
Berries Berryinfo1( "Raspberries", 7);
Berryinfo1.GetBerryInfo();
system("pause");
return 0;
}
A couple of points on your mistakes:
GetBerryInfo() was declared inside the class. You don't need to re-declare it in the global scope. That 2nd declaration should be removed.
To be invoked, functions (like GetBerryInfo) must have () at the end of them like so: GetBerryInfo().
There is no point for GetBerryInfo() to take Berries as a paremeter. It is a member function that is part of the class Berries. It has access to all data members of a Berries instance already.
You don't need to use cout here: cout << GetBerryInfo; because the function body already sends the data members to cout. This function returns void so it doesn't make sense to send this to cout anyway.
hi everyone im new to programming so excuse the noob question...
i tried every method to get through with the undefined refernce error but it keeps throwing that error at me
i tried using pointer "->" and the "::" sign and also the dot "."
what am i supposed to do? why cant it compile?
this is my cpp file:
#include <cstdlib>
#include "account.hpp"
using namespace std;
int Account::getAccountNumber()
{
return accountNumber;
}
double Account::getBalance()
{
return balance;
}
void Account::createAccount(LinkedList<Account>& accountsList, string name, int idNumber)
{
...
case 1:
accountsList.addFront(newAcc); //Where the error occurs.
break;
case 2:
do
{
cout << "\n\tWhich position would you like to insert the\n"
<< "\tnew account into?\n"
<< "\tPosition number: #";
cin >> target;
if (cin.fail())
{
cin.clear();
cin.ignore(20,'\n');
cout << "\n\n\tSorry, wrong input. Please enter a correct position.\n\n";
system("pause");
}
}
while(cin.fail());
accountsList.addMiddle(newAcc, target); //and here
break;
case 3:
accountsList.addEnd(newAcc); //and here
break;
}
cout << "\n\n\tAccount Created Successfully\n\n"
<< accountsList;
system("pause");
}
and here is my .hpp
#ifndef ACCOUNT_HPP_INCLUDED
#define ACCOUNT_HPP_INCLUDED
#include "linkedlist.hpp"
#include "generic.hpp"
class Account : public GenericAccount
{
int accountNumber;
double balance;
public:
Account(string name = "empty", int idNumber = 0, int accountNumber = 0, double balance = 0)
: GenericAccount(name, idNumber), accountNumber(accountNumber), balance(balance) {}
int getAccountNumber();
double getBalance();
void createAccount(LinkedList<Account>&, string, int);
void deposit(LinkedList<Account>&, Account&);
void withdraw(LinkedList<Account>&, Account&);
void displayAccount(LinkedList<Account>&, Account&);
void deleteAccount(LinkedList<Account>&);
friend istream& operator>> (istream& is, Account& x)
{
is >> x.accountNumber;
return is;
}
friend ostream& operator << (ostream& os, Account& c)
{
os << "Account Number= " << c.getAccountNumber() << "\t"
<< "Balance= "<< c.getBalance() << endl;
return os;
}
friend bool operator == (Account& a, Account& target)
{
return (a.getAccountNumber() == target.getAccountNumber());
}
};
#endif // ACCOUNT_HPP_INCLUDED
the full project can be downloaded HERE for refernce
THANK YOU ALL IN ADVANCE!
I think the issue is that there is that the addFront method is not being defined for the account type (in fact any type). See Why can templates only be implemented in the header file? for a much better explanation.
Moving the contents of cpp inline in the .h file should do the trick. Another option is to rename the the .cpp file to a .inl and include it at the bottom of linkedList.hpp
I'm having an issue with overloading the << operator. Everything prints and enters fine, but when I try and return the ostream, I get this error:
Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
I've also already overloaded another << operator in this project that has returned an ostream just fine. This operator isn't used in the following code. Here's the code:
#include "header1.h"
#include <iostream>
using namespace std;
class Car
{
public:
friend class Extras;
friend int main();
friend ostream& operator<< (ostream& os, const Car& in);
Car();
Car(string in_name, int in_year, string in_color, float in_cost);
private:
string name, color;
int year, extr_num;
float cost;
Extras *extr;
};
int main()
{
Car c1;
cout << c1;
return 0;
}
//Default Constructor
Car::Car()
{
name = "TEMP";
color = "BLUE";
year = 0;
cost = 0;
extr = new Extras[3];
extr_num = 0;
}
//Constructor
Car::Car(string in_name, int in_year, string in_color, float in_cost)
{
name = in_name;
color = in_color;
year = in_year;
cost = in_cost;
extr = new Extras[3];
extr_num = 0;
}
//Overloaded << operator for Car class
//This function is the one that fails.
ostream& operator<< (ostream& os, const Car& in)
{
os.precision(2);
os << in.name << ", " << in.year << ", "
<< in.color << ", $"<< in.cost << ", ";
os << "extras include: ";
os << endl;
return os; //Line of code in question
}
This bit of code in the other header works perfectly fine:
ostream& operator<< (ostream& os, Extras const &in)
{
os << in.ex_list;
return os;
}
Everything prints to the screen fine before the return. And these two functions look the same to me, can someone more experience with C++ tell me otherwise?
There's nothing in the shown code that will cause the problem you describe. The "_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)" error is an indication that the heap was corrupted at an earlier point, it's being detected at your return statement but isn't otherwise related to the code in your operator<<
You've hosed your heap. It may or may not have anything to do with the code currently running. Don't see anything immediately apparent in what you've decided to show us that would cause it though I'd start with any use of raw pointers.