假设输入文件包含以下内容,每个文件对应于struct中的四个成员:
0 2 54 34
1 2 43 56
4 5 32 67
因此,例如,在输入文件的第一行中,我希望将0存储为离开站点ID,将2存储为到达站点ID,将54存储为离开时间,将34存储为到达时间。
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <list>
#include <vector>
#include <utility>
#include "graph.h"
using namespace std;
int main(int argc, char **argv)
{
ifstream file;
struct TrainsFile{
vector<int> departureStationId;
vector<int> arrivalStationId;
vector<int> departureTime;
vector<int> arrivalTime;
};
vector<TrainsFile> trains;//creating vector of structs here
file.open(argv[1]);
if (file.is_open())
{
//How does one use push_back() here given that I am dealing with vectors within vectors?
while(!file.eof())
{
file >> departureStationId >> arrivalStationId >> departureTime >>
arrivalTime;
}
}
}
答案 0 :(得分:1)
根据您陈述的目标和示例数据文件,我认为您的发展方向很糟糕。似乎您需要文件中的火车列表,而不是火车文件列表。这样一来,vector
中的TrainsFile
便消失了,并消除了您的问题。
通过快速重命名结构,我们得到
struct Train
{
int departureStationId;
int arrivalStationId;
int departureTime;
int arrivalTime;
};
如果我们将文件的读取从
while(!file.eof())
{
file >> departureStationId >> arrivalStationId >> departureTime >> arrivalTime;
}
为了operator>>
超载以保持清洁
std::istream &operator >>(std::istream & in, Train & train)
{
return in >> train.departureStationId
>> train.arrivalStationId
>> train.departureTime
>> train.arrivalTime;
}
然后我们可以将the faulty while loop重写为
Train train;
while (file >> train)
{
trains.push_back(train);
}
这将循环播放,直到无法从文件中读取火车为止。
完全组装的示例:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
struct Train
{
int departureStationId;
int arrivalStationId;
int departureTime;
int arrivalTime;
};
std::istream &operator >>(std::istream & in, Train & train)
{
return in >> train.departureStationId
>> train.arrivalStationId
>> train.departureTime
>> train.arrivalTime;
}
int main(int argc, char **argv)
{
ifstream file;
vector<Train> trains; //creating vector of structs here
// strongly recommend testing argc to make sure there ID an argv[1] here
file.open(argv[1]);
if (file.is_open())
{
Train train;
while (file >> train)
{
trains.push_back(train);
}
}
}
由于每行似乎只有一列火车,对此的一种改进是to use std::getline
从文件中提取一行,然后use a std::istringstream
从该行中提取一列火车。这将使您能够更好地检测格式错误的文件并从中恢复。有关此方法的演示,请参见Read file line by line using ifstream in C++。
答案 1 :(得分:0)
创建新变量(供阅读)
int departureId, arrivalId, departureT, arrivalT;
在循环中:
while(file >> departureId >> arrivalId>> departureT >> arrivalT)
{
TrainsFile trainsfile;
trainsfile.departureStationId.push_back(departureId);
trainsfile.arrivalStationId.push_back(arrivalId);
trainsfile.departureTime.push_back(departureT);
trainsfile.arrivalTime.push_back(arrivalT);
trains.push_back(trainsfile);
}//other code
只需将这些变量放入正确的对象中,然后推动您的主向量