main.cpp

来自「利用栈知识来模拟停车场系统」· C++ 代码 · 共 91 行

CPP
91
字号
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <stdexcept>
#include <string>
#include <stack>

using namespace std;
#include "Car.h"

int main(int argc,char *argv[])
{
	if (argc != 2) {
        cerr << "Usage: " << argv[0] << " data-file\n";
        return EXIT_FAILURE;
    }

    try {
        string file = argv[1];
		ifstream in;
		//Open the file
		in.open(file.c_str());
		if(!in)
		{
			throw exception("Can not open the file");
		}
		//The file has been open,we declar a stack as the parking lot aisle
		stack<Car*> aisle;
		string action;//The action of the car from the text file
		string license;//The license of the car from the text file
		while(1)
		{
			in>>license;
			in>>action;
			if(action=="arrives")
			{
				if(aisle.size()==5)
				{
					cout<<"Sorry "<<license<<", the lot is full"<<endl;
				}else
				{
					Car *car=new Car(license);
					aisle.push(car);
				}
			}else
				if(action=="departs")
				{
					stack<Car*> tempStore;
					Car * tempCar;
					int count=aisle.size();
					while(!aisle.empty())
					{
						tempCar=aisle.top();
						if(tempCar->getLicense()==license)
						{
							cout<<*tempCar;
							aisle.pop();
							delete tempCar;
							break;
						}else
						{
							aisle.pop();
							tempCar->movedTimesIncrease();
							tempStore.push(tempCar);
						}
					}
					if(tempStore.size()==count)
					{
						cout<<"Can not find the car "<<license<<endl;
					}
					while(!tempStore.empty())
					{
						aisle.push(tempStore.top());
						tempStore.pop();
					}
				}
			if(in.eof())
			{
				break;
			}
		}
    }
    catch(exception& e) {
        cerr << e.what() << endl;
    }
    catch(...) {
        cerr << "Unknown exception caught!" << endl;
    }
    
    return EXIT_FAILURE;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?