时刻表.txt
我所设计的时刻表如下图所示,由一条条的时刻记录组成,分别为:
出发地、目的地、车次、发车时间、到站时间、费用、交通工具
时刻表的阅读较简单,没有过多的输入限制,但必须按照这七个属性次序填写
test.txt
读取方式
1.值的存储
//attribute.h
#ifndef ATTRIBUTE_H
#define ATTRIBUTE_H
#include <QString>
#include <QTime>
class Attribute
{
public:
Attribute();
Attribute(int, int, QString, QString, QString, int, int);
int from, to, cost, vehicle;
QString num;
QString begin, end;
};
#endif // ATTRIBUTE_H
//attribute.cpp
#include "attribute.h"
Attribute::Attribute()
{
this->from = -1;
}
//这个类用来保存时刻表txt文件的一组内容,由myschedule类中读取并调用
Attribute::Attribute(int from, int to, QString num, QString begin, QString end, int cost, int vehicle)
{
this->from = from;
this->to = to;
this->num = num;
this->begin = begin;
this->end = end;
this->cost = cost;
this->vehicle = vehicle;
}
以上为一个attribute类,仅用作容器值处理,在后续multimap容器中使用,是键值对中值的数据类型
2.如何读取txt文件
//myschedule.h
#ifndef MYSCHEDULE_H
#define MYSCHEDULE_H
#include "attribute.h"
#include <vector>
#include <map>
#include <utility>
#include <algorithm>
#include <QString>
#include <QObject>
#include <QDateTime>
#include <QFile>
#include <QTextStream>
#include <QDebug>
struct schedule{
QString trainnum;
int starttime;
int endtime;
int cost;
int vihecle;
};
class MySchedule
{
public:
MySchedule();
~MySchedule();
static int CityToNum(QString);
static std::multimap<int, Attribute> database;
schedule ***head;
private:
void store_in_schedule();
};
#endif // SCHEDULE_H
//myschedule.cpp
#include "myschedule.h"
#include <QDebug>
#define CityNum 15
std::multimap<int, Attribute> MySchedule::database;
MySchedule::MySchedule()
{
for(int i = 0;i < CityNum;i++)
{
database.erase(i);
}
QFile file(":/test.txt");
if(!file.open(QIODevice::ReadOnly))//只读方式打开文件,打开失败时输出失败
{
qDebug() << "Can't open the file";
return;
}
QTextStream in(&file);
QString from, to, number, begin, end, cost, vechile; //分别为出发地、目的地、班次、开始时间、结束时间、费用、交通方式
//将时刻表信息读入database数据结构
while(!in.atEnd())
{
in >> from >> to >> number >> begin >> end >> cost >> vechile >> endl;//读取一组时刻信息
if(from != "") //from没有读到信息时不进入分支
{
// qDebug() << from << to << number << begin;
Attribute line(CityToNum(from), CityToNum(to), number, begin, //声明对象line将一组信息保存到其中
end, cost.toInt(), vechile.toInt());
database.insert(std::make_pair(CityToNum(from), line)); //insert函数为database插入pair数据,由于键值与元素是多对多对应关系,
} //multimap称为多重映照容器,后期学习vector、list容器,相比map容器multimap
} //允许键值重复插入元素,后期学习multimap的元素搜索
store_in_schedule();
}
MySchedule::~MySchedule()
{
}
//CityToNum是一个将QString装换位int类型的函数,在此不列举进来了
关于多重映照容器multimap的使用在此也不过多赘述
搜索multimap即可