Question

I am having trouble understanding how this code is able to use the contents of the...

I am having trouble understanding how this code is able to use the contents of the header file. Can someone please provide brief comments in the top code to show what is happening?

THE CODE:

#include<bits/stdc++.h>
#include "MyCartesianPoint.h"
#include <math.h>
#include <iostream>

using namespace std;

bool isNumber(string s)
{
   if(!isdigit (s[0]))
   {
       if(s[0] != '-')
       return false;
      
       else if(s.length() == 1)
       return false;
   }
  
   for (int i = 1; i < s.length(); i++)
   if (isdigit(s[i]) == false)
  
   return false;
   return true;

}

int main()
{
   string x, y;
   int X, Y;

CartesianPoint::SetLimit(10);
vector<CartesianPoint> v;
CartesianPoint origin(0,0);
v.push_back(origin);
cout << "You will be travelling from (0, 0) to (10, 10) in as many steps as you like. Enter (10, 10) to end.\n";
  
do
{
   cout << "Move from " << v.back().ToString() << " to where? ";
   CartesianPoint p;
  
       cout << "\nX:";
   while(true)
   {
       cin >> x;
         
       if(isNumber(x))
       {
               try
           {
               X = stoi(x);
                   p.SetX(X);
                   break;
           }
               catch(exception& e)
               {
                   //if there is an exception
                   cout << "* Invalid input. " << e.what() << " ";
               }
           }
         
       else
       cout << "* Invalid input. Please try again and enter a numeric value. ";
   }
  
   cout << "Y:";
     
   while(true)
   {
       cin >> y;
         
       if(isNumber(y))
       {
           try
           {
                   Y = stoi(y);
                   p.SetY(Y);
                   break;
               }
              
               catch(exception& e)
               {
                   // If there is an exception:
                   cout << "* Invalid input. " << e.what() << " ";
               }
           }
          
       else
       cout << "* Invalid input. Please try again and enter a numeric value. ";
   }
  
// Insert into v:
v.push_back(p);
  
}

while(X != 10 || Y != 10);
  
double dist = 0;
cout << "DEBUGGING ONLY:\n";
for(int i = 0; i < v.size() - 1; i++)
{
   double d = v[i].GetDistanceTo(v[i + 1]);
   cout << v[i].ToString() << " -> " << v[i + 1].ToString() << ": " << fixed << setprecision(2) << d << endl;
  
   dist += d;
}
cout << "\nFINAL OUTPUT:\n";
cout << "The total distance between " << v.size() << " points is " << fixed << setprecision(2) << dist << ".";
}

HEADER FILE:

#ifndef MY_CARTESIAN_POINT_H

#define MY_CARTESIAN_POINT_H

#include <iostream>        // cin, cout
#include <sstream>            // stringstream
#include <cmath>           // sqrt()
#include <limits>           // INT_MAX
#include <stdexcept>       // out_of_range

using namespace std;

// class declaration section
class CartesianPoint
{
public:
/* Constructor: Used to initialize objects */
CartesianPoint(int x = 1, int y = 1) { SetPoint(x, y); }
  
/* Accessors: Used to query the state of the object */
   int GetX() const { return myX; }
   int GetY() const { return myY; }
  
// get the distance between this point and a second point
    double GetDistanceTo(CartesianPoint pointTo) const;
    string ToString() const; // convert the obj to a string.  
  
/* Mutators: Used to change the state of the object */
   void SetX(int x) { myX = validateCoordinateValue(x); }
   void SetY(int y) { myY = validateCoordinateValue(y); }
   void SetPoint(int x, int y) { SetX(x); SetY(y); }  
  
/* Static methods:
       - Can be used to access/mutate static data members
       - Can be called without an object
   */
   // get the limit
   static int GetLimit() { return sharedLimit; }
   // set the limit
   static void SetLimit(int limit) { sharedLimit = abs(limit); }

/* Friend Functions: Nonmember functions/methods that are granted the same
        privileges as member methods
*/
// TO-DO: Add ReadCartesianPoint() to the friends list
   
     
private:
// private data members for the dimensions of the point
int myX; // x-axis (horizontal) value
int myY; // y-axis (vertical) value
  
// Static data-member: Shared among all objects of this class.
   static int sharedLimit;
  
// Helper method for validation
int validateCoordinateValue(int value) const;

};

// Class definition section

/** sharedLimit static data-member for CartesianPoint class
*   Used to validate the x and y coordinate values.
*/
int CartesianPoint::sharedLimit = INT_MAX;

/** GetDistanceTo Method for CartesianPoint class
*   Determines the distance between this point and a second point.
*   @param   pointTo: CartesianPoint
*   @return   the distance as a double
*/
double CartesianPoint::GetDistanceTo(CartesianPoint pointTo) const
{
int xDelta = pointTo.myX - myX; // difference between x values
int yDelta = pointTo.myY - myY; // difference between y values
// return the formula (based on Pythagorean theorem)
   return sqrt((xDelta * xDelta) + (yDelta * yDelta));
}

/** ToString Method for CartesianPoint class
*   Converts the obj to a string.
*   @return   the obj state as a string
*/
string CartesianPoint::ToString() const
{
   // declare a stringstream object
   stringstream strOut;
   // build the string
   strOut << "(" << myX << ", " << myY << ")";
   // return the string
   return strOut.str();
}

/** validateCoordinateValue Method for CartesianPoint class
*   Determines if the parameter is valid for a coordinate value.
*   @param   value (int)
*   @return   the parameter if valid
*   @throws an out_of_range exception if not in range
*/

int CartesianPoint::validateCoordinateValue(int value) const
{
   // if the parameter is within the limits
   if((value < -sharedLimit || value > sharedLimit))
   {
       // throw an exception
       throw out_of_range( "Parameter (" + to_string(value) + ") must be between "
           + to_string(-sharedLimit) + " and " + to_string(sharedLimit) + ".");
   }
  
   return value;
}

#endif

0 0
Add a comment Improve this question Transcribed image text
Answer #1

I have tried to explain how header file has been used in the main program through comments.I have highlighted those in bold .Also go through the mehod i have mentioned in code for better understanding

--------------------------------

main.cpp

#include<bits/stdc++.h>
#include "MyCartesianPoint.h"
#include <math.h>
#include <iostream>

using namespace std;

bool isNumber(string s)
{
if(!isdigit (s[0]))
{
if(s[0] != '-')
return false;
else if(s.length() == 1)
return false;
}
for (int i = 1; i < s.length(); i++)
if (isdigit(s[i]) == false)
return false;
return true;

}

int main()
{
string x, y;
int X, Y;
//This is defined in header file.This set the limit that the point
//coordinates must be between the limit ie 10 here.Used in cordinate class for validation of point
//coodinates.

CartesianPoint::SetLimit(10);
//create a vector of CartesianPoint class defined in header file.
vector<CartesianPoint> v;
CartesianPoint origin(0,0);//Create an object of CartesianPoint class.Initialization is in header file as CartesianPoint(int x = 1, int y = 1)
v.push_back(origin);
cout << "You will be travelling from (0, 0) to (10, 10) in as many steps as you like. Enter (10, 10) to end.\n";

do
{
cout << "Move from " << v.back().ToString() << " to where? ";
CartesianPoint p;

cout << "\nX:";
while(true)
{
cin >> x;

if(isNumber(x))
{
try
{
X = stoi(x);
p.SetX(X);
break;
}
catch(exception& e)
{
//if there is an exception
cout << "* Invalid input. " << e.what() << " ";
}
}

else
cout << "* Invalid input. Please try again and enter a numeric value. ";
}

cout << "Y:";

while(true)
{
cin >> y;

if(isNumber(y))
{
try
{
Y = stoi(y);
p.SetY(Y);
break;
}

catch(exception& e)
{
// If there is an exception:
cout << "* Invalid input. " << e.what() << " ";
}
}

else
cout << "* Invalid input. Please try again and enter a numeric value. ";
}

// Insert into v:
v.push_back(p);

}

while(X != 10 || Y != 10);

double dist = 0;
cout << "DEBUGGING ONLY:\n";
for(int i = 0; i < v.size() - 1; i++)
{
double d = v[i].GetDistanceTo(v[i + 1]);//this method is defined in header file as double CartesianPoint::GetDistanceTo(CartesianPoint pointTo) const
//and calulates the distance of an point form another

cout << v[i].ToString() << " -> " << v[i + 1].ToString() << ": " << fixed << setprecision(2) << d << endl;

dist += d;
}
cout << "\nFINAL OUTPUT:\n";
cout << "The total distance between " << v.size() << " points is " << fixed << setprecision(2) << dist << ".";
}

---------------------------------

MyCartesianPoint.h //////////This is same as earlier

#ifndef MY_CARTESIAN_POINT_H

#define MY_CARTESIAN_POINT_H

#include <iostream> // cin, cout
#include <sstream> // stringstream
#include <cmath> // sqrt()
#include <limits> // INT_MAX
#include <stdexcept> // out_of_range

using namespace std;

// class declaration section
class CartesianPoint
{
public:
/* Constructor: Used to initialize objects */
CartesianPoint(int x = 1, int y = 1)
{
SetPoint(x, y);
}

/* Accessors: Used to query the state of the object */
int GetX() const
{
return myX;
}
int GetY() const
{
return myY;
}

// get the distance between this point and a second point
double GetDistanceTo(CartesianPoint pointTo) const;
string ToString() const; // convert the obj to a string.

/* Mutators: Used to change the state of the object */
void SetX(int x)
{
myX = validateCoordinateValue(x);
}
void SetY(int y)
{
myY = validateCoordinateValue(y);
}
void SetPoint(int x, int y)
{
SetX(x);
SetY(y);
}

/* Static methods:
- Can be used to access/mutate static data members
- Can be called without an object
*/
// get the limit
static int GetLimit()
{
return sharedLimit;
}
// set the limit
static void SetLimit(int limit)
{
sharedLimit = abs(limit);
}

/* Friend Functions: Nonmember functions/methods that are granted the same
privileges as member methods
*/
// TO-DO: Add ReadCartesianPoint() to the friends list


private:
// private data members for the dimensions of the point
int myX; // x-axis (horizontal) value
int myY; // y-axis (vertical) value

// Static data-member: Shared among all objects of this class.
static int sharedLimit;

// Helper method for validation
int validateCoordinateValue(int value) const;

};

// Class definition section

/** sharedLimit static data-member for CartesianPoint class
* Used to validate the x and y coordinate values.
*/
int CartesianPoint::sharedLimit = INT_MAX;

/** GetDistanceTo Method for CartesianPoint class
* Determines the distance between this point and a second point.
* @param pointTo: CartesianPoint
* @return the distance as a double
*/
double CartesianPoint::GetDistanceTo(CartesianPoint pointTo) const
{
int xDelta = pointTo.myX - myX; // difference between x values
int yDelta = pointTo.myY - myY; // difference between y values
// return the formula (based on Pythagorean theorem)
return sqrt((xDelta * xDelta) + (yDelta * yDelta));
}

/** ToString Method for CartesianPoint class
* Converts the obj to a string.
* @return the obj state as a string
*/
string CartesianPoint::ToString() const
{
// declare a stringstream object
stringstream strOut;
// build the string
strOut << "(" << myX << ", " << myY << ")";
// return the string
return strOut.str();
}

/** validateCoordinateValue Method for CartesianPoint class
* Determines if the parameter is valid for a coordinate value.
* @param value (int)
* @return the parameter if valid
* @throws an out_of_range exception if not in range
*/

int CartesianPoint::validateCoordinateValue(int value) const
{
// if the parameter is within the limits
if((value < -sharedLimit || value > sharedLimit))
{
// throw an exception
throw out_of_range( "Parameter (" + to_string(value) + ") must be between "
+ to_string(-sharedLimit) + " and " + to_string(sharedLimit) + ".");
}

return value;
}

#endif

Add a comment
Know the answer?
Add Answer to:
I am having trouble understanding how this code is able to use the contents of the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I am having trouble understanding how this code is able to use the contents of the...

    I am having trouble understanding how this code is able to use the contents of the header file. Can someone please provide comments in the main code to describe what is happening? (especially on the bool isNumber) THE MAIN CODE: #include<bits/stdc++.h> #include "MyCartesianPoint.h" #include <math.h> #include <iostream> using namespace std; bool isNumber(string s) {    if(!isdigit (s[0]))    {        if(s[0] != '-')        return false;               else if(s.length() == 1)        return false;...

  • Why is the assertion failing? what code can fix the problem and where should that code...

    Why is the assertion failing? what code can fix the problem and where should that code be located at? class Point { public: Point() { myX = myY = 0; } Point(int n, int y) { myx = x; myy = y; } int getX() const { return myX; } int getY() const { return myY; } virtual void read(istream& in) { in >> myX >> myY; } private: int myx, myY; }; class Point3D : Public Point { public:...

  • Extend the code from Lab6.A template is given to you with CircleHeader.h, Circle.cpp and CircleMain.cpp Use...

    Extend the code from Lab6.A template is given to you with CircleHeader.h, Circle.cpp and CircleMain.cpp Use the same Circle UML as below and make extensions as marked and as needed. Given below is a UML for the Painting Class. You will need to write PaintingHeader.h and Painting.cpp. The Painting Class UML contains a very basic skeleton. You will need to flesh out this UML and add more instance variables and methods as needed. You do NOT need to write a...

  • c++, I am having trouble getting my program to compile, any help would be appreciated. #include...

    c++, I am having trouble getting my program to compile, any help would be appreciated. #include <iostream> #include <string> #include <string.h> #include <fstream> #include <stdlib.h> using namespace std; struct record { char artist[50]; char title[50]; char year[50]; }; class CD { //private members declared private: string artist; //asks for string string title; // asks for string int yearReleased; //asks for integer //public members declared public: CD(); CD(string,string,int); void setArtist(string); void setTitle(string); void setYearReleased(int); string getArtist() const; string getTitle() const; int...

  • I am having trouble understanding the concept of polymorphism. I know that I only need to...

    I am having trouble understanding the concept of polymorphism. I know that I only need to edit the MathDriver.java (driver) class, but I am not entirely sure how. Here is my MathDriver.java driver class, the one that I need to finish: Here is the parent class, Math.java: Lastly, here are the child classes, Addition, Subtraction, and Multiplication Given the following program, finish the driver class to demonstrate polymorphism. Program: PolyMath Copy and paste your driver class into the textbox for...

  • A library maintains a collection of books. Books can be added to and deleted from and...

    A library maintains a collection of books. Books can be added to and deleted from and checked out and checked in to this collection. Title and author name identify a book. Each book object maintains a count of the number of copies available and the number of copies checked out. The number of copies must always be greater than or equal to zero. If the number of copies for a book goes to zero, it must be deleted from the...

  • Please help fix my code C++, I get 2 errors when running. The code should be...

    Please help fix my code C++, I get 2 errors when running. The code should be able to open this file: labdata.txt Pallet PAG PAG45982IB 737 4978 OAK Container AYF AYF23409AA 737 2209 LAS Container AAA AAA89023DL 737 5932 DFW Here is my code: #include <iostream> #include <string> #include <fstream> #include <vector> #include <cstdlib> #include <iomanip> using namespace std; const int MAXLOAD737 = 46000; const int MAXLOAD767 = 116000; class Cargo { protected: string uldtype; string abbreviation; string uldid; int...

  • The following C++ code include 3 files: Patient.h, Patient.cpp and Main.cpp. The program basically creates and stores patient records. The original code has everything in a single .cpp file. I tried t...

    The following C++ code include 3 files: Patient.h, Patient.cpp and Main.cpp. The program basically creates and stores patient records. The original code has everything in a single .cpp file. I tried to divide the code in 3 parts (Patient.h, Patient.cpp and Main.cpp), but it is giving me errors. Patient.h #ifndef PATIENT_H #define PATIENT_H #include <string> #include "Patient.cpp" using namespace std; class Patient{ private : string firstname; string lastname; string location; static int cnt; int id; public : Patient(string, string, string);...

  • How can I make this compatible with older C++ compilers that DO NOT make use of...

    How can I make this compatible with older C++ compilers that DO NOT make use of stoi and to_string? //Booking system #include <iostream> #include <iomanip> #include <string> using namespace std; string welcome(); void print_seats(string flight[]); void populate_seats(); bool validate_flight(string a); bool validate_seat(string a, int b); bool validate_book(string a); void print_ticket(string passenger[], int i); string flights [5][52]; string passengers [4][250]; int main(){     string seat, flight, book = "y";     int int_flight, p = 0, j = 0;     int seat_number,...

  • This is my code that i need to finish. In BoxRegion.java I have no idea how...

    This is my code that i need to finish. In BoxRegion.java I have no idea how to create the constructor. I tried to use super(x,y) but It is hard to apply. And Also In BoxRegionHashTable, I don't know how to create displayAnnotation BoxRegion.java ------------------------------------------------ public final class BoxRegion { final Point2D p1; final Point2D p2; /** * Create a new 3D point with given x, y and z values * * @param x1, y1 are the x,y coordinates for point...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT