Input Question

Hi everybody,
I am working on a class that takes the coordinates of two points and calculates the slope and distance between them. However, I would like to have the values to be taken as user input, rather than always having to go back and change them. What would be the most efficient way to do this? I tried the cin operator and for some reason it gives me non-sense. Thanks. Code is below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 #include<iostream>
#include<cmath>

using namespace std;

class Point {
	double x1, y1, x2, y2;
	
public:
	void set_values (double, double, double, double);
	double slope(){return (y2-y1)/(x2-x1);}
	double distance() {return sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));} 
};

void Point::set_values (double nx1, double ny1, double nx2, double ny2) {
	x1 = nx1;
	y1 = ny1;
	x2 = nx2;
	y2 = ny2;
}

int main() {
	Point point;
	cout << "Enter the x and y coordinates of the two points: " << endl;
	point.set_values(1.0, 1.0, 4.0, 5.0);
	cout << "The slope of the line going through the points is " << point.slope() << endl;
	cout << "The distance between the two points is " << point.distance() << endl;
	return 0;
}
1
2
class Point {
	double x1, y1, x2, y2;

A point has just a single x,y value. What you seem to be modelling here is a line rather than a point.

Last edited on
Yes, the naming is non appropriate. but it is just a name, I could have called it artichoke. :)
As for the input, you could define an overload for the input operator >>

This is just a beginning:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <cmath>

using namespace std;

class Point {
    double x, y;
    
public:
    friend std::istream& operator >> (std::istream& is, Point& p)
    {
        is >> p.x >> p.y;
        return is;
    }
    
    friend std::ostream& operator << (std::ostream& os, const Point& p)
    {
        os << '(' << p.x << ',' <<  p.y << ')';
        return os;
    }
    
    
};

// Line defined by two Points
class Line {
    Point a, b;
    // etc.
    // etc.
};

int main() 
{
    Point point;
    cout << "Enter the x and y coordinates of the point: " << endl;
    cin >>  point;
    
    
    cout << "The point is: " << point << endl;
    
}
Topic archived. No new replies allowed.