Hello everybody, I'm new to programming and today I'm here because I need help with a simple exercise that I'm trying to solve. The exercise consists of various small parts :
1) Define a struct called Point with two x and y coordinates (double).
2) Prompt the user to enter 7 (x,y) pairs.
3) As we read those pairs we have to store them in a vector of Points called original_points.
So this is my first attempt :
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
|
struct Point {
double x;
double y;
};
istream& operator>>(istream& is, Point& p)
{
char ch1;
if (is >> ch1 && ch1 != '(') {
is.unget();
is.clear(ios_base::failbit); // oops format error
return is;
}
double v1, v2;
char ch2, ch4;
is >> v1 >> ch2 >> v2 >> ch4;
if (!is || ch2 != ',' || ch4 != ')') error("Bad reading"); // messed up reading
p.x = v1;
p.y = v2;
return is;
}
void skip_to_character(char character)
{
if (cin.fail()) {
cin.clear();
for (char ch; cin >> ch;) {
if (ch == character) {
cin.unget();
return;
}
}
}
if (cin.eof()) error("No input\n");
}
int main()
try {
cout << "Please enter seven (x,y) coordinates : \n";
vector<Point> original_points;
for (int i = 0; i < 7; ++i) {
Point p;
cin >> p;
skip_to_character('('); // let's try to recover from a simple format error
original_points.push_back(p);
}
}
catch (runtime_error& e) {
std::cerr << "Error : " << e.what() << '\n';
}
catch (...) {
cerr << "Unexpected error \n";
}
| |
If a simple format error occurs, I try to recover by skipping every character until the program reaches a '('. My problem is that if I try to enter a wrong input format such as : 9,99)
the code will push_back() both the first correct reading after the error and also the first one before the error occurred. So for example if I try to input such data :
(1,2)
9,99)
(5,6)
I will have three elements in my vector : (1,2), (1,2)
again, and (5,6). It seems like when I get into the loop after every condition check
the value of P remains the same. Could you help me please with this problem ? Why is this error occurring ? Thank you ?