Write a program using C++ that accomplishes each of the following requirements:
ID: 3777550 • Letter: W
Question
Write a program using C++ that accomplishes each of the following requirements:
1. Create a class Point that contains the private integer data members xCoordinate and yCoordinate and declares stream insertion and stream extraction overloaded operator function as friends of the class.
2. Define the stream insertion and stream extraction operator functions. The stream extraction operator function should determine whether the data entered is valid, and, if not, it should set the failbit to indicate improper input. The stream insertion operator should not be able to display the point after an input error occurred.
3. Write a main function that tests input and output of class Point, using the overloaded stream extraction and stream insertion operators.
Your design should include three files, each responsible for one of the requirements.
Explanation / Answer
PROGRAM CODE:
Point.h
/*
* Point.h
*
* Created on: 27-Nov-2016
* Author: kasturi
*/
#ifndef POINT_H_
#define POINT_H_
#include <iostream>
using namespace std;
class Point
{
private:
int xCoordinate;
int yCoordinate;
public:
friend ostream& operator<<(ostream & out, Point &p);
friend istream& operator>>(istream & in, Point &p);
};
#endif /* POINT_H_ */
Point.cpp
/*
* Point.cpp
*
* Created on: 27-Nov-2016
* Author: kasturi
*/
#include <iostream>
#include "Point.h"
#include <cmath>
#include <ios>
using namespace std;
ostream & operator<<(ostream & out, Point &p)
{
out<<"X: "<<p.xCoordinate<<" Y: "<<p.yCoordinate<<endl;
return out;
}
istream & operator>>(istream & in, Point &p)
{
// setting the failbit state if the input coordinates are less than zero or if they are not number
in>>p.xCoordinate>>p.yCoordinate;
if(isnan(p.xCoordinate) || isnan(p.yCoordinate))
in.setstate(std::ios::failbit);
if(p.xCoordinate <0 || p.yCoordinate < 0)
in.setstate(std::ios::failbit);
return in;
}
main.cpp
/*
* main.cpp
*
* Created on: 27-Nov-2016
* Author: kasturi
*/
#include "Point.h"
#include <ios>
int main()
{
Point p;
cout<<"Enter input: ";
cin>>p;
// the failbit is already set . hence cin will now be true for fail
// cout will happen only when fail is false
if(!cin.fail())
cout<<p;
return 0;
}
OUTPUT:
Run #1:
Enter input: 2 3
X: 2 Y: 3
Run #2:
Enter input: -1 4
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.