爲什麼這段代碼不想加載文本文件中的所有值?它只能正確加載第一個對象的項目,但之後它開始變得奇怪。下面是代碼:從文本文件中加載對象數據
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
class Location
{
public:
Location()
{
locName = "No Name";
locDesc = "No Description";
locID = 0;
}
friend ostream& operator <<(ostream& outs, const Location & showMe)
{
// keeping output same as input...
outs << showMe.locName << endl;
outs << showMe.locDesc << endl;
outs << showMe.locID << endl;
return outs;
}
friend istream& operator >>(istream& ins, Location & inLoc)
{
getline(ins, inLoc.locName);
getline(ins, inLoc.locDesc);
ins >> inLoc.locID;
return ins;
}
private:
string locName;
string locDesc;
int locID;
};
int main()
{
ifstream inFile;
inFile.open("loc_data.txt");
if (inFile.fail())
{
cout << "\nCould not open the input file!";
exit(1);
}
Location fileLoc[10];
int i = 0;
while (inFile.good())
{
inFile >> fileLoc[i];
i++;
}
for (int j = 0; j < 10; j++)
cout << fileLoc[j];
return 0;
}
輸入文件是:
Town Hall
Main venue for functions
1
City Park
Outdoor venue
2
Train Station
Commuting point
3
Local Airport
Long distance travel
4
,輸出是:
Town Hall
Main venue for functions
1
City Park
0
No Name
No Description
0
No Name
No Description
0
No Name
No Description
0
No Name
No Description
0
No Name
No Description
0
No Name
No Description
0
No Name
No Description
0
No Name
No Description
0
我有一個suspucion即函數getline負責這一點,但不知道足以確定,但我真的很想知道爲什麼會發生這種情況,而不僅僅是「修復」。
你有文件是什麼?你怎麼知道哪個字段在哪裏結束? – Jagannath