为什么这段代码不想加载文本文件中的所有值?它只能正确加载第一个对象的项目,但之后它开始变得奇怪。下面是代码:从文本文件中加载对象数据
#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