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 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;
   }
  
   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 << ".";
}

THE 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

Explanation with comment: The input number of X and Y is taken as string and passed to isNumber function to check if it is valid number or not. This is how it works:

bool isNumber(string s)
{

   // since number can be negative check if first digit is negative sign "-"
if(!isdigit (s[0]))
{

   // first digit is neither number nor '-1' which is not valid so return false
if(s[0] != '-')
return false;

// first symbol is '-' means negative number
// But if length is 1 it means only '-' in input which is not valid
else if(s.length() == 1)
return false;
}
//check for remaining chracters if they are valid
for (int i = 1; i < s.length(); i++)
// if any of input digit is not a number return false
if (isdigit(s[i]) == false)
       return false;

// all conditions satisfied so return true.
return true;
}

How does file inclusion works?

#include "MyCartesianPoint.h"

This line means that compiler search for file name "MyCartesianPoint.h" in current directory as well as specified list of directories in include path

Had it been written like #include <MyCartesianPoint.h> It would have searched for specified list by compiler only. Not even the current directory. That's why #include <bits/stdc++.h> is written to save searching time. Even writing #include "bits/stdc++.h" will work. Try this to see.

Now in header file "MyCartesianPoint.h"

#ifndef MY_CARTESIAN_POINT_H
#define MY_CARTESIAN_POINT_H

and at last

#endif is used.

This are also known as guards to avoid multiple declaration error. Understand the basics first. : On finding #include "MyCartesianPoint.h" the compiler expands it into the oringal file. Now here only one header file is used so treat it simply as if both have been written in same file. Now but why do we need guards? Here even if you remove them it would cause no error as only one header file is used. But it there was one more file say hello.cpp which was included in The main code and hello.cpp also included "MyCartesianPoint.h" then compiler would give error if there are no guards. Reason=> See when #include "MyCartesianPoint.h" included all functions were expanded in main file. When hello.cpp was included it's function were also included. Now hello.cpp contained"MyCartesianPoint.h" so it had the functions of "MyCartesianPoint.h" already in it and they were also added to main. Now main contains each function of "MyCartesianPoint.h" twice. And what happens if anything is more than once?

Say int a= 5; int a=5; ?

It will give multiple declaration error.

So guards avoid this. They cause inclusion only once.

#ifndef MY_CARTESIAN_POINT_H
#define MY_CARTESIAN_POINT_H

On encountering first time MY_CARTESIAN_POINT_H is not defined so it defines it. But when hello.cpp causes "MyCartesianPoint.h" to get included again MY_CARTESIAN_POINT_H is defined so it does not get included. (ifndef means if not defined)

======

if(isNumber(x)) => check if input is valid number

X = stoi(x); => stoi() converts string into integer

v[i].GetDistanceTo(v[i + 1]); =>v[i] is object of Cartesian Point class. It has function GetDistanceTo() which takes another point as input which is v[i+1].

Until we reach 10,10 do while loop keeps on working.Each path from and to points are pushed in vector v. Then we calculate distance for each path and print it. And in whole process header file is used just like if it is declared in main code itself.

Please comment if you still have any doubts.

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 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...

  • 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,...

  • Hi guys! I need help for the Data Structure class i need to provide implementation of...

    Hi guys! I need help for the Data Structure class i need to provide implementation of the following methods: Destructor Add Subtract Multiply Derive (extra credit ) Evaluate (extra credit ) ------------------------------------------------------- This is Main file cpp file #include "polynomial.h" #include <iostream> #include <sstream> using std::cout; using std::cin; using std::endl; using std::stringstream; int main(int argc, char* argv[]){    stringstream buffer1;    buffer1.str(        "3 -1 2 0 -2.5"    );    Polynomial p(3);    p.Read(buffer1);    cout << p.ToString()...

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