Have to enter the input twice

Hi, I have written a function to overload <<.
The while loops are to check if the input is int or double, and reject it if it is not the correct input.
When the code is ran, and an int is input as desired, you have to input twice for the program to accept it.
I am aware this is due to having is >> xin and then while(!(is>>xin)) - does anyone have any suggestions of other ways of doing this?

Apart from that it works fine.
Thanks :)


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
// Function to overload >>
template <class T>
std::istream & operator>>(std::istream &is, coords<T> &c) {
	T xin, yin;
	cout << "Please input the x co-ordinate:" << endl;
	is >> xin;
	while(!(is>>xin)){
		cout << "Error: Invalid input." << endl;
		is.clear();
		is.ignore();
		cout << "Please re-input the x co-ordinate:" << endl;
		is >> xin;
	}
	cout << "Please input the y co-ordinate:" << endl;
	is >> yin;
	while(!(is>>yin)){
		cout << "Error: Invalid input." << endl;
		is.clear();
		is.ignore();
		cout << "Please re-input the y co-ordinate:" << endl;
		is >> yin;
	}
	c.setx(xin);
	c.sety(yin);
	return is;
}
if you are making a coord class, why make it templatized? a simply this:
struct coords{double x, y;};

To fix your problem remove lines 6, 12, 15 and 21
@Smac89: you make the assumption that all uses of coordinate systems require (or can even allow) real numbers. There are plenty of scenarios where it is more beneficial or even required to use integers instead. And who's to say you can't have coordinates from some other type, like complex numbers?
Thanks, great help!
Topic archived. No new replies allowed.