The main() function should display an appropriate
thrown error message if non-numeric or negative values are entered for any of
the data members.
can someone help me to write the main function
here is my code
#include <iostream>
using namespace std;
class RealEstate
{
private:
int price;
int bedroomNumb;
int bathsNumb;
public:
RealEstate(int p, int bed, int bath)
{
price = p;
bedroomNumb = bed;
bathsNumb = bath;
}
friend ostream &operator<<(ostream &out, const RealEstate &r);
friend istream &operator>>(istream &in, RealEstate &r);
};
istream &operator>>(istream &in, RealEstate &r)
{
cout << "Enter Real Estate Price: ";
in >> r.price;
cout << "Enter Numbers of Bedroom: ";
in >> r.bedroomNumb;
cout << "Enter Numbers of Baths: ";
in >> r.bathsNumb;
return in;
}
ostream &operator<<(ostream &out, const RealEstate &r)
{
out << "Price: " << r.price << endl;
out << "Bedroom: " << r.bedroomNumb << endl;
out << "Baths: " << r.bathsNumb << endl;
return out;
}
int main()
{
}
From what I understand you would like to have a few try and catches in your main(), and throws in the functions that are accepting user input. If that is the case, you should definitely make use of the throw keyword within your functions. In your main, you would
int main(){
try{
function() //note that the function you are calling here should throw an error of type char* and throw this error if the number input by the user is negative and non-numeric.
}catch(const char* msg)
}
That is a brief explanation of how you would implement Error Handling (given the program and information you have provided).
Hope this helps!
Related
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.
Why cout is not working inside a function that overloads the istream operator of C++(>>)?What should I do to make it work?
In the line: cout >> "Enter x and y: " shows an error?
Why?
How can I fix it?
This is the code to overload >> and operator <<
#include<iostream>
using namespace std;
class myClass
{
int x,y;
public:
myClass(int a,int b)
{
x=a;y=b;
}
friend istream &operator>>(istream &in, myClass &ob);
friend ostream &operator<<(ostream &out, myClass ob);
};
istream &operator>>(istream &in,myClass &ob)
{
cout >> "Enter x and y: ";
in >> ob.x;
in >> ob.y;
return in;
}
ostream &operator<<(ostream &out,myClass ob)
{
out << ob.x << " " << ob.y << endl;
}
int main()
{
myClass ob(10,20);
cout << ob;
cin >> ob;
cout << ob;
}
Your error is that you are mixing up << and >>, cout>>"Enter x and y: "; should be cout << "Enter x and y: ";
Also it's not good style to prompt the user in an overloaded operator>>. What if your >> was being used to read from a file? You wouldn't want to prompt the user then. So move cout<<"Enter x and y: "; to the main function where it belongs.
Like this
istream &operator>>(istream &in,myClass &ob)
{
in>>ob.x;
in>>ob.y;
return in;
}
int main()
{
myClass ob(10,20);
cout<<ob;
cout<<"Enter x and y: ";
cin>>ob;
cout<<ob;
return 0;
}
When I input the value for the string types, for examples:
_ho I typed Peter
_hoten I typed Peter Parker
_ten I typed Marry
My output on the screen was:
Peter Peter Marry
Here is my code:
class SinhVien
{
private:
string _ho;
string _tenlot;
string _ten;
public:
static int InstanceCount;
SinhVien();
string ToString() const;
friend istream& operator>>(istream& in, SinhVien* p);
friend ostream& operator<<(ostream& out, const SinhVien* p);
~SinhVien();
};
istream& operator>>(istream& in, SinhVien *p)
{
cout << "Nhap ho: \n";
in >> p->_ho;
rewind(stdin);
cout << "Nhap ten lot: \n";
in >> p->_tenlot;
rewind(stdin);
cout << "Nhap ten: \n";
in >> p->_ten;
return in;
}
string SinhVien::ToString() const
{
stringstream writer;
writer << _ho << " " << _tenlot << " " << _ten << "\n";
return writer.str();
}
ostream& operator<<(ostream &out, const SinhVien* p)
{
out << p->ToString();
return out;
}
void main()
{
SinhVien *a;
a = new SinhVien();
cin >> a;
cout << a;
cout << "\nTo string:\n";
cout << a->ToString();
delete a;
system("pause");
}
In your std::basic_istream::operator>> overload, you need to use std::geline() instead of std::cin >>, so that you can get complete input name with spaces.
Secondly, you should pass the reference of the object pointer, so that the change will be applied to the passed object, not to its copy.
Fix:
std::istream& operator>>(std::istream& in, SinhVien* &p)
{ // ^^ take ref of object you pass, so that the change will be applied to the object, not to the copy of it.
std::cout << "Nhap ho: \n";
std::getline(in, p->_ho); // change
std::rewind(stdin);
std::cout << "Nhap ten lot: \n";
std::getline(in, p->_tenlot); // change
std::rewind(stdin);
std::cout << "Nhap ten: \n";
std::getline(in, p->_ten); // change
return in;
}
Above will work for one single input. However, the case of multiple inputs and use of std::cin >> in the main() can cause again some input skipping problems. Thanks to #Yksisarvinen pointing this out.
You can read more in this SO post: Why does std::getline() skip input after a formatted extraction?
Side note: In modern C++, you do not need to manage the raw pointers, anymore. Because you have smart pointers which will manage your object's lifetime as it goes out of scope. So use it whenever its possible.
That means you can do something like this: SEE LIVE
#include <memory>
class SinhVien
{
private: // memebrs
public:
// other member functions
friend istream& operator>>(istream& in, const std::unique_ptr<SinhVien> &p);
friend ostream& operator<<(ostream& out, const std::unique_ptr<SinhVien> &p);
};
std::istream& operator>>(std::istream& in, const std::unique_ptr<SinhVien> &p)
{
std::cout << "Nhap ho: \n";
std::getline(in, p->_ho); // change
std::cout << "Nhap ten lot: \n";
std::getline(in, p->_tenlot); // change
std::rewind(stdin);
std::cout << "Nhap ten: \n";
std::getline(in, p->_ten); // change
return in;
}
std::ostream& operator<<(std::ostream &out, const std::unique_ptr<SinhVien> &p)
{
return out << p->ToString();
}
int main()
{
auto a = std::make_unique<SinhVien>();
std::cin >> a;
std::cout << a;
std::cout << "\nTo string:\n";
std::cout << a->ToString();
return 0;
}
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.
I was wondering if enumeration is commonly used with user input. I'm doing an exercise in which in my Book class I have to create an enum Genre with different genre enumerators such as fiction, non, fiction etc.
When the user uses the program, he/she is asked for certain information about the book being stored. For a genre, normally I would just do this with a string function and restrict it to certain names with if statements.
However, I'm not sure how to accomplish the same process with an enumerated type, nor do I know if it's even supposed to be used for that sort of thing. Here is the code if you're interested.
#include "std_lib_facilities.h"
//Classes-----------------------------------------------------------------------
class Book{
public:
Book(){}; // default constructor
//operators
friend ostream& operator<<(ostream& out, const Book& val);
bool Book::operator==(const Book& check)
//enumerators
enum Genre{
fiction, nonfiction, periodical, biography, children};
//member functions
string title();
string author();
int copyright();
void ISBN();
bool checkout();
private:
string title_;
string author_;
int copyright_;
int ISBN1;
int ISBN2;
int ISBN3;
char ISBN4;
bool checkout_;
};
// Error Function---------------------------------------------------------------
void _error(const string& s)
{
cout << endl;
cout << "Error: " << s << endl;
cout << endl;
}
// Member Functions-------------------------------------------------------------
string Book::title()
{
cout << "Title: ";
getline(cin,title_);
cout << endl;
return title_;
}
string Book::author()
{
cout << "Author: ";
getline(cin,author_);
cout << endl;
return author_;
}
int Book::copyright()
{
cout << "Copyright: ";
cin >> copyright_;
cout << endl;
return copyright_;
}
void Book::ISBN()
{
cout << "ISBN (Use spaces): ";
cin >> ISBN1 >> ISBN2 >> ISBN3 >> ISBN4;
if((ISBN1<0) || (ISBN2<0) || (ISBN3<0) || (ISBN1>9) || (ISBN2>9) || (ISBN3)>9)
_error("Must be single digit.");
else if(!isdigit(ISBN4) && !isalpha(ISBN4))
_error("Must be single digit or letter.");
else{ cout << endl;
return;}
}
bool Book::checkout()
{
char check;
cout << "Checked out?(Y or N): ";
cin >> check;
switch(check){
case 'Y':
cout << endl;
return true;
break;
case 'N':
cout << endl;
return false;
break;
default:
_error("Must be Y or N.");}
}
// Operator Overloads-----------------------------------------------------------
ostream& operator<<(ostream& out, const Book& val){
out << "Title: " << val.title_ << endl;
out << "Author: " << val.author_ << endl;
out << "ISBN: " << val.ISBN1 << "-" << val.ISBN2 << "-" << val.ISBN3 << "-" << val.ISBN4 << endl;
out << endl;
return out;}
bool Book::operator==(const Book& check){
return((ISBN1 == check.ISBN1) && (ISBN2 == check.ISBN2) && (ISBN3 == check.ISBN3)
&& (ISBN4 == check.ISBN4));}
// Main-------------------------------------------------------------------------
int main()
{
bool finished = false;
char notfinished;
while(!finished)
{
Book book;
book.title();
book.author();
book.copyright();
book.ISBN();
book.checkout();
cout << "Do you wish to store another book?(Y or N): ";
cin >> notfinished;
if(notfinished == 'Y'){
cin.ignore();
cout << endl;}
else if(notfinished == 'N') finished = true;
else _error("Must be Y or N");
}
keep_window_open();
}
Note that some things aren't being used at the moment because the feature they are a part of hasn't been fully implemented yet (storing in a library, outputting books, etc.)
So what would it take to accept user input for the enumerators listed, if even possible? I was thinking something along the lines of making a Genre variable. Then having a function where the user inputs for cin>>variable. However, I'm guessing that the function wouldn't understand an input like 'fiction' and would only accept the enumerator values and input.
Make Genre a class that wraps the enum type (GenreTypeEnum). Add the necessary operators, e.g. istream, ostream, equal operator, etc.
Inside the istream operator, you can read a std::string from the stream and then parse and convert the value to the associated GenreTypeEnum.
Something like this perhaps:
namespace GenreType { enum GenreTypeEnum { miscellaneous, fiction, non_fiction, children }; }
class Genre
{
public:
Genre() : genreType( GenreType::miscellaneous) {}
~Genre() {}
void setType( std::string genreTypeString ){ // implement string-> enum }
std::string toString( void ) const { // convert genre back to string }
private:
GenreType::GenreTypeEnum genreType;
};
std::ostream& operator<<( std::ostream& os, const Genre& genre )
{
os << genre.toString();
return os;
}
std::istream& operator>>( std::istream& is, Genre& genre )
{
std::string input;
is >> input;
genre.setType( input );
return is;
}
C-style enums are not terribly useful for this purpose, since there's no way to recover the original string name. You could make some switch-based mechanism, but at that point you may as well just set up your own way of doing it all that works with your user I/O requirements without shoehorning.
One of the ways to handle this is to set up a map of strings to enum values. Other possibilities include a dedicated function.
See this question for some ideas.
This question has some ideas of how to generate code to convert enums to strings, but most of the examples will work in reverse as well.