如果您正在使用C++流和希望做一些與數據,我會做到這一點的方法是:
std::istream& operator<<(std::istream& i, Data& d)
{
if (!(i >> d.member) || !(i >> d.othermember))
d.markInvalid(); // the istream is automatically marked invalid
return i;
}
// In another function:
Data myData;
while (std::cout << "Please enter the data: " &&
std::cin >> myData) // Or another stream, of course)
{
if (!data.isValid())
{
std::cout << "Invalid data.\n";
continue;
}
// Operate on data
}
這給你一個意外的EOF不會有循環運行和優勢沒有gotos。如果您希望繼續輸入錯誤,只需將第二個&&
更改爲||
並進行循環檢查myData.isValid()
,並在出現故障時顯示錯誤消息continue;
。
或者,如果你正在寫一個函數讀取並返回數據(不是很優雅,在我看來),你可以使用
Data GetData(std::ostream& o, std::istream& i) {
Data myData;
while (o << "Please enter the data: " &&
i >> myData.member &&
i >> myData.otherMember &&
!myData.isValid())
{
o << "Invalid data! Please try again.\n";
}
if (!i)
{
myData.markInvalid(); // Make sure the caller knows the data is not good.
// Alternatively, throw an exception.
}
return myData;
}
// In another function:
Data myData = GetData(std::cout, std::cin);
if (myData.isValid())
{
// Operate on data
}
在這兩種情況下,你可能不能夠完全創建對象,並將需要某種方式來報告。您需要檢查是否輸入了錯誤格式的數據(然後您可能會忽略無效輸入以便您可以獲得新輸入),或者數據流是否死亡(在這種情況下,您可能需要保釋出)。 C++ FAQ有關於此問題的一些信息here,包括使用整型類型執行此類操作的函數示例。
您認爲B和C之間的區別是什麼? – Archie
這是功課嗎? –
哈哈@「最好」。什麼是「最好」? 「最佳」爲了什麼?據誰?什麼時候?在什麼條件下?通過什麼指標? –