📄 main.cpp
字号:
#include <iostream>
#include <fstream>
#include <stack>
#include "car.h"
using namespace std;
int main(int argc, char *argv[])
{
ifstream ifs("data.txt");//open file
if(!ifs){
cerr<<"Can't open the in file "<<endl;
exit(-1);
}
ofstream ofs("output.txt");//open file
if(!ofs){
cerr<<"Can't open the out file "<<endl;
exit(-1);
}
stack<car *> stack_;// stack to simulate the park lot
stack<car *> temp_stack_;//stack to store the cars been moved in order to make the object out
car * point_to_car;
string license_tag;
string action;// arrives or departs
while(!ifs.eof())
{
ifs>>license_tag>>action;
if(action == "arrives"){// a car arrives
if(stack_.size() <5){// to check if there is space left
point_to_car = new car(license_tag);// generate a pointer to the car
stack_.push(point_to_car);// the pointer enter stack
}
else
ofs<<"Sorry "<<license_tag<<" , the lot is full"<<endl;
}
else if(action == "departs")// when a car departs
{
while(!stack_.empty()&&stack_.top()->get_license_plate() != license_tag){//the object car is not in the top
temp_stack_.push(stack_.top());// enter the temporary stack
stack_.top()->move();//move times increase
stack_.pop();//go out the stack
}
if(stack_.top()->get_license_plate() == license_tag){// the object car is in the top now
ofs<<stack_.top()->get_license_plate()<<" was moved "<<stack_.top()->get_move_times()<<" times while it was here"<<endl;
delete stack_.top();//delete the object
stack_.pop();// pop the pointer
}
else
ofs<<"Accident!"<<endl;
while(!temp_stack_.empty()){//put the cars back from the temporary stack to the stack
stack_.push(temp_stack_.top());
temp_stack_.pop();
}
}
}
for(;!stack_.empty();){//output the number of times each car that remains in the lot (if there are any) was moved
ofs<<stack_.top()->get_license_plate()<<" moved "<<stack_.top()->get_move_times()<<" times while it was here"<<endl;
delete stack_.top();
stack_.pop();
}
ofs.close();//close file
ifs.close();
cout<<"Task finished! The result is in the file output.txt. "<<endl;
return 1;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -