-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcoordinate.cpp
More file actions
102 lines (80 loc) · 1.65 KB
/
coordinate.cpp
File metadata and controls
102 lines (80 loc) · 1.65 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "coordinate.h"
#include <string>
#include <algorithm>
#include <sstream>
Coordinate::Coordinate()
{
x = y = 0;
}
Coordinate::Coordinate(int x, int y)
{
this->x = x;
this->y = y;
}
Coordinate::Coordinate(const Coordinate& c)
{
this->x = c.getX();
this->y = c.getY();
}
void Coordinate::setX(int x)
{
this->x = x;
}
void Coordinate::setY(int y)
{
this->y = y;
}
int Coordinate::getX() const
{
return x;
}
int Coordinate::getY() const
{
return y;
}
std::ostream& operator << (std::ostream& out, Coordinate& c)
{
out << "(" << c.getX() << ", " << c.getY() << ")";
return out;
}
std::istream& operator >> (std::istream& in, Coordinate& c) throw (const char*)
{
std::string line;
std::getline(in, line);
const char* ERROR = "Invalid coordinate input, must be '(x, y)' format where x and y are legal integers";
int end = line.size() - 1;
//Remove the parentheses and comma leaving a format of 'x y'
if (line[0] == '(' && line[end] == ')' && line.find(',') != std::string::npos)
{
line.erase(end, 1);
line.erase(0, 1);
int pos = 0;
for (pos; pos < line.size(); pos++)
{
if (line[pos] == ',')
break;
}
line.erase(pos, 1);
}
else
throw ERROR;
//Check the coordinates...
end = line.size() - 1;
for (int i = 0; i < line.size(); i++)
{
if (!(isdigit(line[i]) ||
(line[i] == ' ') ||
(line[i] == '-' && i != end && isdigit(line[i + 1]))))
{
throw ERROR;
}
}
//parse with string stream
std::stringstream ss(line);
int x, y;
ss >> x >> y;
//set the retrieved values
c.setX(x);
c.setY(y);
return in;
}