how to print using iterator in c++? - c++

I am writing a program in VC++. Here I am declaring class Product and Client.In client I'm using a function list initProduct() in which list::iterator i; is used.I'm unable to display list using iterator.
This my code:
#include "StdAfx.h"
#include <iostream>
#include <string>
#include <list>
#include <iterator>
using namespace std;
class Product
{
int item_code;
string name;
float price;
int count;
public:
void get_detail()
{
cout<<"Enter the details(code,name,price,count)\n"<<endl;
cin>>item_code>>name>>price>>count;
}
};
class Client
{
public:
list<Product> initProduct()
{
char ans='y';
list<Product>l;
list<Product>::iterator i;
while(ans=='y')
{
Product *p = new Product();
p->get_detail();
l.push_back(*p);
cout<<"wanna continue(y/n)"<<endl;
cin>>ans;
}
cout<<"*******"<<endl;
for(i=l.begin(); i!=l.end(); i++)
cout << *i << ' '; //ERROR no operator << match these operand
return l;
}
};
int main()
{
Client c;
c.initProduct();
system("PAUSE");
}

You must implement the following function
class Product {
// ...
friend std::ostream& operator << (std::ostream& output, const Product& product)
{
// Just an example of what you can output
output << product.item_code << ' ' << product.name << ' ';
output << product.price << ' ' << product.count;
return output;
}
// ...
};
You declare the function a friend of the class because it must be able to access the private properties of a Product.

You need to produce an ostream& operator<<(ostream& os, const Product& product) that prints the information you want to display.

If you're using C++11 you can use auto :
for(auto it : Product)
{
cout << it.toString();
}
but you'll have to implement this toString() which will display all the infos you want

Related

How would I use a friend method that is predefined in a header file?

Essentially, my Computer Science teacher is making me use the friend std::ostream method for output.. I have imported it into the header file as one can see below, but I have no clue how to use it in the student.cpp. Adding student::ostream did not work. How would I be able to use the header predefined method in my student.cpp
My header file
#pragma once
#include <iostream>
class student
{
public:
student();
std::string settingStudentName;
bool disiplineIssue();
// provided again so you learn this valuable override method for printing class data.
friend std::ostream& operator << (std::ostream& const student &);
private:
std::string studentName;
bool hasDisciplineIssue;
};
Student.cpp
#include "student.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
student::student()
{
}
bool student::disiplineIssue()
{
// Max the random integer can go
int max = 100;
srand(time(0));
int random = rand()%max;
// bool variable for returning
bool True_or_False = false;
if (random <= 5)
{
True_or_False = true;
}
return True_or_False;
}
ostream& operator<< (ostream& output, const student& aStudent) {
output << aStudent.studentName << " ";
if (aStudent.hasDisciplineIssue) {
output << "has ";
}
else {
output << "doesn't have ";
}
output << "a discipline issue";
return output;
}
Edit:
When I do not have student:: in front, ostream works but if I add student:: in front, it says it can not resolve the symbol. I am not sure if the one without student:: is using the one I defined in the header file.
I would proceed in the following manner:
add body and declaration parameters to function settingStudentName in both header and main file;
insert correct dependancies (#include);
add a main() driver function;
also, use correct syntax (friend std::ostream& operator << (std::ostream&, const student &);) lacked the comma , separator between the function arguments.
A MWE:
#ifndef STUDENT_H_INCLUDED
#define STUDENT_H_INCLUDED
#include <iostream>
#include <string>
class student
{
public:
student();
std::string settingStudentName(const std::string&);
bool disiplineIssue();
// provided again so you learn this valuable override method for printing class data.
friend std::ostream& operator << (std::ostream&, const student &);
private:
std::string studentName;
bool hasDisciplineIssue;
};
#endif // STUDENT_H_INCLUDED
#include "student.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
student::student()
{
}
string student::settingStudentName(const string& input)
{
studentName = input;
return input;
}
bool student::disiplineIssue()
{
// Max the random integer can go
int max = 100;
srand(time(0));
int random = rand()%max;
// bool variable for returning
bool True_or_False = false;
if (random <= 5)
{
True_or_False = true;
}
return True_or_False;
}
ostream& operator<< (ostream& output, const student& aStudent) {
output << aStudent.studentName << " ";
if (aStudent.hasDisciplineIssue) {
output << "has ";
}
else {
output << "doesn't have ";
}
output << "a discipline issue";
return output;
}
int main()
{
student Jack;
Jack.settingStudentName("Jack");
Jack.disiplineIssue();
cout << Jack << endl;
return 0;
}
Here is the output:
Jack has a discipline issue
And here is a compiled version you can play with https://wandbox.org/permlink/mF49xQxkXs3M7n0M

How can I overload the << operator so I can write the data of an object to a file?

I have an object of type piggyBank and I need to write data of this object into a file and then read it. I am aware of how to write/read to a text file but how can I overload the << operator so I can write data about the object into a file?
My code for the class here:
piggyBank.h
#include <string>
#ifndef PIGGYBANK_H
#define PIGGYBANK_H
class PiggyBank
{
private:
std::string owner;
int balance;
bool broken;
int id;
static int nrOfObjects;
public:
PiggyBank(void);
PiggyBank(std::string name);
std::string getOwnerName() const;
void setOwnerName(std::string name);
bool isBroken() ;
int getBalance(int & amount) ;
};
#endif /* PIGGYBANK_H */
piggyBank.cpp
#include "PiggyBank.h"
#include "readWrite.h"
#include <string>
#include <iostream>
using namespace std;
int PiggyBank::nrOfObjects = 0; // outside constructor
PiggyBank::getNrOfObjects(){
return nrOfObjects;
}
PiggyBank::PiggyBank(void){
{this->owner="";this->balance=0;this->broken=false;}
id = ++nrOfObjects;
}
PiggyBank::PiggyBank(std::string name, int startBalance){
{this->owner=name;this->balance=startBalance;this->broken=false;}
id = ++nrOfObjects;
}
string PiggyBank::getOwnerName() const{
return this->owner;
}
void PiggyBank::setOwnerName(string name){
this->owner = name;
}
bool PiggyBank::isBroken() {
return this->broken;
}
int PiggyBank::getBalance(int & amount) {
if(!broken){
amount = balance;
return 0;
}else{
return -1;
}
}
You want the << operator to be a friend to the class and to return ostream&.
Here is a simple example to get an idea about how it works.
friend ostream& operator << (ostream& os, const PiggyBank& obj)
{
// For example something like this
os << "Information that you want to output to the file:\n";
os << "Owner: " << obj.owner << "\n";
return os;
}
And then you can use it like this:
PiggyBack obj;
ofstream fout("file.txt");
// also check to see if the file opened correctly
if(fout.fail())
{
cout << "File failed to open\n";
return 0;
}
fout << obj;
// now you have written the owner information onto the file as well as the message before it
// inside the operator<< overload
// close the resource at the end
fout.close();
The cool part is that you can use it to print to the console too by changing fout to be cout.
For example:
cout << obj; // will print to the console
Very simple. Overload the inserter operator. Write this into your class:
friend std::ostream& operator << (std::ostream& os, const PiggyBank& pb) {
return os << pb.owner << . . . // Whatever you want
Then you can use the inserter operator as for any other data type:
int main() {
PiggyBank pb;
if (std::ofstream os("FileName"); os) {
os << pb << "\n";
}
return 0;
}

C2678 being thrown for no apparent reason to me

I am trying to compile this project just to see how I am doing as I go along, but I still have a few more classes to implement that will inherit from Widget for different types. When I compile I keep getting C2678:
Error C2678 binary '==': no operator found which takes a left-hand
operand of type 'Widget' (or there is no acceptable conversion)
Assignment10 c:\program files (x86)\microsoft visual
studio\2017\community\vc\tools\msvc\14.11.25503\include\xutility line3107
I cant find where this error is thrown or why. Any help would be greatly appreciated. Sorry it's so sloppy, I've been messing with it a lot to try and find the problem.
#pragma once
#include <iostream>
using namespace std;
class Widget
{
public:
int idNumber;
//structors
Widget()
{
idNumber = 0;
}
Widget(int a)
{
idNumber = a;
}
~Widget();
//operations
int getId()
{
return idNumber;
}
//overload operators to compare idNumber
void operator= (Widget &rhs)
{
idNumber = rhs.idNumber;
}
};
----------------------------------------
#include "Widget.h"
#include <iostream>
using namespace std;
Widget::~Widget()
{
}
/*
bool Widget::operator< (Widget &rhs)
{
bool result;
result = idNumber < rhs.idNumber;
return result;
}*/
---------------------------------
#pragma once
#include "Widget.h"
#include <list>
#include <iostream>
using namespace std;
class Inventory
{
public:
Inventory();
Inventory(int i)
{
Widget w(i);
}
~Inventory();
//operations
//process order for shipment
void order(int widgID);
//recieve widget
void receive(int widgID);
//overlaod output operator
friend ostream& operator<<(ostream&, const Widget&);
protected:
list<Widget> onHand;
list<int> onOrder;
};
-------------------------------
#include "Inventory.h"
#include "Widget.h"
#include <iostream>
#include <list>
using namespace std;
Inventory::Inventory()
{
Widget w;
}
Inventory::~Inventory()
{
}
//recieve widget
void Inventory::receive(int widgID)
{
cout << " Recieved shipment of Widget type "
<< widgID << endl;
//find the iterator of the widget location
list<int>::iterator weNeed;
weNeed = find(onOrder.begin(), onOrder.end(), widgID);
//if end is returned, item not found
if (weNeed != onOrder.end())
{
cout << "Ship " << Widget(widgID) << " to fill back order" << endl;
onOrder.erase(weNeed);
}
else
{
onHand.push_front(Widget(widgID));
}
}
//process order
void Inventory::order(int widgID)
{
cout << " Recieved order for Widget type "
<< widgID << endl;
//find the iterator of the widget location
list<Widget>::iterator weHave;
weHave = find(onHand.begin(), onHand.end(), widgID);
//if end is returned, item not found
if (weHave != onHand.end())
{
cout << "Ship " << *weHave << endl;
onHand.erase(weHave);
}
else
{
cout << "Back order widget of type "
<< widgID << endl;
onHand.push_front(Widget(widgID));
}
}
ostream& operator<<(ostream& os, const Widget& wid)
{
os << wid.idNumber;
return os;
}

Retrieving values of an object from an array?

Pardon the example but in this case:
#include <iostream>
#include <string>
using namespace std;
class A {
private:
string theName;
int theAge;
public:
A() : theName(""), theAge(0) { }
A(string name, int age) : theName(name), theAge(age) { }
};
class B {
private:
A theArray[1];
public:
void set(const A value) {theArray[0] = value; }
A get() const { return theArray[0]; }
};
int main()
{
A man("Bob", 25);
B manPlace;
manPlace.set(man);
cout << manPlace.get();
return 0;
}
Is it possible for me to retrieve the contents of the "man" object in main when I call manPlace.get()? My intention is to print both the name (Bob) and the age (25) when I call manPlace.get(). I want to store an object within an array within another class and I can retrieve the contents of said array within the main.
You need to define a ostream::operator<< on your A class to accomplish that - otherwise the format how age and name should be generated as text-output is undefined (and they are private members of your A class).
Take a look at the reference for ostream::operator<<. For your A class, such a operator could be defined like this:
std::ostream& operator<< (std::ostream &out, A &a) {
out << "Name: " << a.theName << std::endl;
out << "Age: " << a.theAge << std::endl;
return out;
}
Which would output something like:
Name: XX
Age: YY
So your complete code would be:
#include <iostream>
#include <string>
using namespace std;
class A {
private:
string theName;
int theAge;
public:
A() : theName(""), theAge(0) { }
A(string name, int age) : theName(name), theAge(age) { }
friend std::ostream& operator<< (std::ostream &out, A &a) {
out << "Name: " << a.theName << std::endl;
out << "Age: " << a.theAge << std::endl;
return out;
}
};
class B {
private:
A theArray[1];
public:
void set(const A value) { theArray[0] = value; }
A get() const { return theArray[0]; }
};
int main()
{
A man("Bob", 25);
B manPlace;
manPlace.set(man);
cout << manPlace.get();
return 0;
}
which will output:
Name: Bob
Age: 25

debugging error at the end of the console

I'm a student and I studying c++.
This is my cpp code
int _tmain(int argc, _TCHAR* argv[])
{
CFood output;
output.whatFunc();
cout<<"my outputs"<<endl<<output<<endl;
return 0;
}
ostream& operator <<(ostream& outputStream, const CFood& output)
{
for(int i=0; i<2; i++)
{
outputStream <<"1 : "<<output.m_strName[i]<<" 2 : "<<output.m_servingSize[i]<<"g "<<"3 : "<<
output.m_calorie[i]<<"cal "<<"4 : "<<output.m_transFat[i]<<"g"<<endl;
}
return outputStream;
}
When I debug it, It work. But the end of the console, it gives me error message;;;
It says "An unhandled win32 exception occurred in work.exe [5796]"
My header filed is
class CFood
{
public:
CFood(void);
~CFood(void);
private:
string m_strName[7];
double m_servingSize[7];
double m_calorie[7];
double m_transFat[7];
public:
void whatFunc(void);
friend ostream& operator <<(ostream& outputStream,const CFood& output);
}
I think there is something wrong in my code..And I think it's CFood output;(Just thinking..)
Do you know why it has debug error?
++Sorry, I forgot the whatFunc(void)
This is code
void CFood::whatFunc(void) //
{
m_strName[0]="chicken";
m_strName[1]="rice";
m_strName[2]="meat";
m_strName[3]="strawberry";
m_strName[4]="apple";
m_strName[5]="water";
m_strName[6]="juice";
m_servingSize[0]=10;
m_servingSize[1]=20;
m_servingSize[2]=30;
m_servingSize[3]=40;
m_servingSize[4]=50;
m_servingSize[5]=60;
m_servingSize[6]=70;
m_calorie[0]=10.45;
m_calorie[1]=20.57;
m_calorie[2]=30.78;
m_calorie[3]=40.23;
m_calorie[4]=50.85;
m_calorie[5]=60.73;
m_calorie[6]=70.27;
m_transFat[0]=0.01;
m_transFat[1]=0.02;
m_transFat[2]=0.03;
m_transFat[3]=0.04;
m_transFat[4]=0.05;
m_transFat[5]=0.06;
m_transFat[6]=0.07;
}
Well its difficult to tell what exactly goes wrong without full source code. In my humble opinion, entire source lefts much to be desired. Placing obviously linked data in the bunch of the unlinked arrays with static size is not a very good pattern. Instead try something like that:
#include <iostream>
#include <vector>
#include <string>
#include <ostream>
struct CFoodItem{
std::string m_strName;
double m_servingSize;
double m_calorie;
double m_transFat;
};
class CFood
{
public:
void AddFoodItem(const CFoodItem& cItem);
friend std::ostream& operator <<(std::ostream& outputStream, const CFood& output);
private:
std::vector<CFoodItem> m_vItems;
};
std::ostream& operator <<(std::ostream& outputStream, const CFood& output)
{
for (auto i = output.m_vItems.begin(); i != output.m_vItems.end(); ++i)
{
outputStream << "1 : " << i->m_strName << " 2 : " << i->m_servingSize << "g " << "3 : " <<
i->m_calorie << "cal " << "4 : " << i->m_transFat << "g" << std::endl;
}
return (outputStream);
}
void CFood::AddFoodItem(const CFoodItem& cItem)
{
m_vItems.push_back(cItem);
}
int __cdecl main(void)
{
CFood output;
CFoodItem itm;
itm.m_strName = "some food";
itm.m_servingSize = 100500;
itm.m_calorie = 42;
itm.m_transFat = 42;
output.AddFoodItem(itm);
std::cout << "my outputs" << std::endl << output << std::endl;
return 0;
}