您不能測試fin != 0
。 fin
不是一個數字,爲了測試與0的相等程度,使得測試一個蘋果是什麼樣的橙子的意義。你可以通過利用operator bool來測試fin
是否仍然可讀,儘管使用簡單的fin
,但這很棘手,因爲測試是可讀的,將在閱讀之前進行。在您有機會失敗之前,您無法測試失敗,並且會導致上次讀取失敗並且未檢查有效性的可能性。
而不是試圖解決這個問題,我要在這裏go all X-Y在這裏,並建議完全不同的東西。
定義的結構
struct room
{
int room_no;
string room_status;
string category;
int rent; // could be a float. Don't care much for this example
// that said, watch out for rounding errors when dealing with floats
};
創建一個功能,使得它很容易閱讀到這個結構
std::istream & operator>>(std::istream & in,
room & inroom)
{
in >> inroom.room_no >> inroom.room_status >> inroom.category >> inroom.rent;
return in;
}
創建一個功能,使得它很容易編寫這種結構
std::ostream & operator<<(std::ostream & out,
const room & outroom)
{
out << outroom.room_no << setw(10) << outroom.room_status <<
setw(10) << outroom.category << setw(10) << outroom.rent;
return out;
}
使上述結構的std::vector
成員在Hotel
類
std::vector<room> rooms;
的文件讀入到它
room temp;
while (in >> temp)
{
rooms.push_back(temp);
}
現在酒店知悉所有房間的狀態,而無需守望着文件。這使打印變得容易。
for(room & r: rooms)
{
cout << r << '\n';
}
這使得現在發現任何房間房間
for(room & r: rooms)
{
if (r.whatever == desiredwhatever)
{
return r;
}
}
,每一個簡單的遍歷,然後你重寫該文件,如果一個房間被改變。
std::ostream outfile("path to file goes here");
for(room & r: rooms)
{
if (!(outfile << r << '\n'))
{
//handle error
}
}
所有這些事情你可能必須做。唯一的缺點是,如果你不允許使用std::vector
。在這種情況下,你要麼寫一個簡單的vector
替代品,要麼使用數組,並祈禱它永遠不會溢出。
你爲什麼試圖比較'fin!= 0'?你期望做什麼? – jtbandes