C++ 从文本文件读取到对象向量
这是我的向量声明:C++ 从文本文件读取到对象向量,c++,vector,C++,Vector,这是我的向量声明: Flight flightSchedule(flightID,departure,destination,price,dateOfFlight,timeOfFlight); 矢量飞行列表; 根据您的要求,假设您的Flight.txt内容为: 印度22 美国23 中国24 vector<Flight> flightList; #包括 #包括 #包括 #包括 使用名称空间std; 无效搜索航班(字符串); 班机 { 公众: 字符串目的地; int tm; 航班(字
Flight flightSchedule(flightID,departure,destination,price,dateOfFlight,timeOfFlight);
矢量飞行列表;
根据您的要求,假设您的Flight.txt内容为:
印度22
美国23
中国24
vector<Flight> flightList;
#包括
#包括
#包括
#包括
使用名称空间std;
无效搜索航班(字符串);
班机
{
公众:
字符串目的地;
int tm;
航班(字符串d,整数t):目的地(d),终点(t)
{
}
字符串getDestination()
{
返回目的地;
}
int displayFlightSchedule()
{
返回tm;
}
};
int main()
{
searchFlight(“印度”);
返回0;
}
无效搜索航班(字符串目的地)
{
矢量飞行列表;
弦线;
int tm;
字符串dest;
ifstream ifs(“Flight.txt”);
while(getline(ifs,line))
{
istringstream是(行);
is>>dest>>tm;
航班列表。向后推(航班(目的地,tm));
}
对于(无符号i=0;iYou可以覆盖运算符>>()
为航班定义一个istream
提取器,并通过一个std::istringstream
来解析每一行,将刚刚在主循环中读取的行包装起来。假设是文件格式的每行一个航班。顺便说一句,我在这里看不到任何问题。需要将字符串解析到对象中吗?问题是cmd wil弹出默认值,但不是文本文件中的值。文件中每行的内容是什么?
vector<Flight> flightList;
#include<iostream>
#include<vector>
#include<fstream>
#include<sstream>
using namespace std;
void searchFlight(string);
class Flight
{
public:
string destination;
int tm;
Flight(string d, int t):destination(d), tm(t)
{
}
string getDestination()
{
return destination;
}
int displayFlightSchedule()
{
return tm;
}
};
int main()
{
searchFlight("India");
return 0;
}
void searchFlight(string destin)
{
vector<Flight> flightlist;
string line;
int tm;
string dest;
ifstream ifs("Flight.txt");
while(getline(ifs, line))
{
istringstream is(line);
is>>dest>>tm;
flightlist.push_back(Flight(dest, tm));
}
for(unsigned i = 0; i<flightlist.size(); i++)
{
if (destin == (flightlist[i].getDestination()))
{
cout<<flightlist[i].displayFlightSchedule()<<endl;
}
}
}