C++primer plus第十章第5题


头文件:

//stack.h

#ifndef _STACK_H
#define _STACK_H

struct customer
{
	char fullname[35];
	double payment;
};

typedef customer Item ;

class Stack
{
private:
	enum {MAX=10};
	Item items[MAX];
	int top;

public:
	Stack();
	virtual ~Stack() {};
	bool isempty() const;
	bool isfull() const;
	bool push(const Item & item);
	bool pop(Item & item);

};


#endif // !_STACK_H

.cpp文件:

//stack.cpp

#include "stack.h"

Stack::Stack()
{
	top = 0;
}

bool Stack::isempty() const
{
	return top == 0;
}

bool Stack::isfull() const
{
	return top == MAX;
}

bool Stack::push(const Item & item)
{
	if (top < MAX)
	{
		items[top++] = item;
		return true;
	}
	else
		return false;
}

bool Stack::pop(Item & item)
{
	if (top > 0)
	{
		item = items[--top];
		return true;
	}
	else
		return false;
}

main:

//main.cpp

#include <iostream>
#include "stack.h"

void get_customer(customer & cu);

using namespace std;

int main()
{
	
	Stack st;
	char ch;
	customer temp;
	double payment = 0;
	cout << "Enter A or a to push a customer,\n"
		<< "P or p to pop a customer,and Q or q to quit!" << endl;
	while ((cin >> ch) && (ch != 'q') && (ch != 'Q'))
	{
		while (cin.get() != '\n')
			continue;
		if ((toupper(ch)!= 'A') && (toupper(ch) != 'P' ))
		{
			cout << "Please enter A,por Q!" << endl;
			continue;

		}
		switch (ch)
		{
		case 'A':
		case 'a':
			if (st.isfull())
				cout << "The stack is already full!" << endl;
			else 
				get_customer(temp);
			st.push(temp);
			break;

		case 'P':
		case 'p':
			if (st.isempty())
				cout << "The stack is empty!" << endl;
			else
			{
				st.pop(temp);
				payment += temp.payment;
				cout << temp.payment << "is poped!";
				cout << "payment now total $" << payment << endl;

			}
			break;
		
		}
		cout << "Enter A or a to push a customer,\n"
			<< "P or p to pop a customer,and Q or q to quit!" << endl;
	
	}
	cout << "Done!" << endl;

	return 0;
}

void get_customer(customer & cu)
{
	cout << "Enter customer name :";
	cin.getline(cu.fullname, 35);
	cout << "Enter customer payment :";
	cin >> cu.payment;
	while (cin.get() != '\n')
		continue;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-03-16 09:37  taxue505  阅读(133)  评论(0编辑  收藏  举报