Context: I am working in a chess project, i want to do input validation in the cin>>bearing operation.
Question 1: is this a good way to do input validation?
Reasons: it makes easier to read what the user has to input and makes easier to write single lane input checker with error message (as showed in the main function).
Question 2: how do i do it?
Possible duplicate: How can we check for invalid input into an overloaded operator?
What's different from that post?: i don't want the overhead caused by raising an exception and catching it (also, i hope it isn't necessary)
This is the code I try to make it work.
#include <iostream>
using namespace std;
struct Bearing
{
unsigned x{};
unsigned y{};
Bearing() = default;
Bearing(unsigned t_x, unsigned t_y) : x{ t_x }, y{ t_y } {}
Bearing(char t_c, unsigned t_y) : x{ static_cast<unsigned>(t_c - 'a') }, y{ t_y - 1 } {}
};
std::istream &operator>>(std::istream &is, Bearing &bearing)
{
char c;
unsigned n;
if (is >> c) {
c = tolower(c);
if ('a' <= c && c <= 'h' && is >> n && 1 <= n && n <= 8) {
// bearing = Bearing(c, n);
bearing = Bearing{ c, n };
return is;
}
}
is.setstate(ios_base::failbit);// register the failure in the stream
return is;
}
int main()
{
std::cout << "Input the piece's letter and number:\n";
Bearing bearing;
while (!(cin >> bearing)) { cout << "wrong input, try again\n"; }
return 0;
}
What happens: It never waits for input again in the loop If i give it a wrong input (becomes a while true loop).
What I expect: to wait for input in each iteration if the input was not the expected.