C++ ssd5 14 recommended exercise4

#pragma once
#include<string>
#ifndef CAR_H
#define CAR_H

using namespace std;

class car
{
private:
string plate;
string action;
int number;
public:
car();
car(string m_plate, string m_action, int m_number);

int getNum();

string getPlate();

void setNum();

string getAction();

friend istream& operator>>(istream& os, car* &car);


};

 

#endif

 

 

 

 

 

 

 

 

 

#include"car.h"

car::car() :plate(""), action(""), number(0)
{
}

car::car(string m_plate,string m_action , int m_number) : plate(m_plate), action(m_action), number(m_number)
{
}

int car::getNum()
{
return number;
}

string car::getPlate()
{
return plate;
}

void car::setNum()
{
number++;
}

string car::getAction()
{
return action;
}

istream& operator>>(istream& is, car* &car)
{
is >> car->plate;
is >> car->action;
return is;
}

 

 

 

 

 

 

#include<iostream>
#include<fstream>
#include<string>
#include"car.h"
#include<stack>

int main(int argc, char* argv[])
{
if (argc != 2)
{
cerr << "there is no file.." << endl;
return EXIT_FAILURE;
}
string file = argv[1];
ifstream in;
in.open(file.c_str());//open the file
if (!in)
{
cerr << "can not opn this file.." << endl;
return 0;
}

stack<car*> aisle = stack<car*>();//lot asile
stack<car*> temp = stack<car*>();//temporary stack for move
while (!in.eof())
{
car* m_car = new car();
in >> m_car;//read by word


if (m_car->getAction() == "arrives" && aisle.size() < 5)//new one come here and lot is not full
{
aisle.push(m_car);
cout << m_car->getPlate() << " " << m_car->getAction() << endl;

}
else if (m_car->getAction() == "departs")//depart
{
cout << m_car->getPlate() << " " << m_car->getAction() << endl;

while (aisle.top()->getPlate() != m_car->getPlate())//move car* to temp stack until found the car which need to depart
{
temp.push(aisle.top());
aisle.top()->setNum();
aisle.pop();

}

cout << aisle.top()->getPlate() << "was moved " << aisle.top()->getNum() << " times while it was here" << endl;
car* temp_pt = aisle.top();
aisle.pop();
delete temp_pt;//no leak memory
delete m_car;//no leak memory

while (!temp.empty())//move car from temp stack to aisle
{
aisle.push(temp.top());
temp.pop();
}

}
else//lot is full
cout << "sorry," << m_car->getPlate() << "the parking lot is full" << endl;

}

while (!aisle.empty())//there is car not leave until now
{
cout << aisle.top()->getPlate() << " was moved " << aisle.top()->getNum() << " while it was here" << endl;
car* temp_pt = aisle.top();
aisle.pop();
delete temp_pt;
}


return 0;
}

posted @ 2016-04-01 16:17  BigMinnow  阅读(204)  评论(0编辑  收藏  举报