【发布时间】:2018-05-01 11:29:47
【问题描述】:
根据我在众多论坛和书籍上阅读的内容,我已经尝试了几次。有关此作业的更多详细信息以及更多代码:Click- another question from StackOverflow
我需要做的是创建一个包含 CHotel 对象的文件并将它们插入到这个向量 m_hoteli 中。
至于为什么它不起作用,它要么没有从文件中读取字符串,要么根本没有填充向量。 这是我的文件:
“码头”5 500
“郁金香”4 400
“黑海”3 300
“瑞士钟”5 600
class CComplex:CHotel
{
protected:
string m_complex;
vector<CHotel> m_hoteli;
public:
CComplex(){};
CComplex(string filename, string nComplex)
{
fstream file("filename.txt", ios::in);
CHotel temp(" ",0,0);
while (file >> temp)
{
m_hoteli.push_back(temp);
}
/* Second try:
m_complex = nComplex;
fstream in;
in.open(filename, ios::in);
string s;
while (getline(in, s))
{
CHotel h1(s);
m_hoteli.push_back(h1);
}
Third try:
m_complex = nComplex;
ifstream iStream(filename);
if (iStream.good())
{
copy(istream_iterator<CHotel>(iStream), istream_iterator<CHotel>(), back_inserter(m_hoteli));
}
}
*/
}
这是 CHotel 代码:
class CHotel : public CTurist
{
protected:
string hName;
int stars;
int beds;
map<CTurist, unsigned> Turisti;
public:
unsigned Sum = 0;
int br = 0;
CHotel(){};
CHotel(string hName2, int zvezdi, int legla)
{
hName = hName;
stars = zvezdi;
beds = legla;
}
friend istream& operator>>(std::istream& is, CHotel& e)
{
is >> e.hName >> e.stars >> e.beds;;
return is;
}
我只是主要这样做:CComplex c1("filename.txt", "Complex1");
【问题讨论】:
-
请注意,使用 istream>> 将逐行读取文件空间而不是逐行
-
@LorenceHernandez:啊,我明白了。这就是为什么逗号不起作用的原因。删除了所有逗号,现在它填充了向量。