![](/img/trans.png)
[英]How do I properly overload the '=' operator to work with an array that is overloading the '[ ]' operator?
[英]Should I do input validation with operator>> overloading and How do I do It?
上下文:我在國際象棋項目中工作,我想在 cin>>bearing 操作中進行輸入驗證。
問題 1:這是進行輸入驗證的好方法嗎?
原因:它更容易閱讀用戶必須輸入的內容,也更容易編寫帶有錯誤消息的單通道輸入檢查器(如主函數所示)。
問題2:我該怎么做?
可能重復: 我們如何檢查對重載運算符的無效輸入?
與那篇文章有什么不同?:我不希望因引發異常並捕獲它而造成的開銷(另外,我希望沒有必要)
這是我試圖讓它工作的代碼。
#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;
}
發生了什么:如果我給它一個錯誤的輸入(變成 while true 循環),它永遠不會在循環中等待再次輸入。
我期望的是:如果輸入不是預期的,則在每次迭代中等待輸入。
正如@Ranoiaetep 所說,“代碼需要清理 state 並在錯誤輸入后忽略之前的輸入”
int main()
{
std::cout << "Input the piece's letter and number:\n";
Bearing bearing;
while (!(cin >> bearing)) {
cout << "wrong input, try again\n";
cin.clear();
cin.ignore(10000, '\n');
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.