c++ primer第五版 第十章编程练习节选(结构体&类)

1.问题描述:

2. 解决方案:

stack.h

#pragma once
#ifndef STACK_H_
#define STACK_H_
struct customer
{
	char fullname[35];
	double payment;
};

typedef customer Item;

class Stack
{
private:
	enum {MAX = 20};
	Item items[MAX];
	int top;
public:
	Stack();
	~Stack();
	bool isempty()const;
	bool isfull()const;
	void push(const Item &item);
	void pop(Item &item);
};
#endif

 stack.cpp

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

using namespace std;

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

Stack::~Stack()
{
	cout << "delete. " << endl;
}

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

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

void Stack::push(const Item &item)
{
	if (top < MAX)
	{
		items[top++] = item;
	}
	else
	{
		cout << "Stack is already full ! " << endl;
	}
}

void Stack::pop(Item &item)
{
	if (top > 0)
	{
		item = items[--top];
	}
	else
	{
		cout << "Stack is already empty ! " << endl;
	}
}

main.cpp

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

using namespace std;

void getCustomer(customer &c);

int main()
{
	Stack st;
	customer c;
	char ch;
	double payment = 0.0;
	cout << "A: to add a customer into stack \n";
	cout << "P: to pop a customer out of stack \n";
	cout << "Q: to quit the program \n";
	cout << "Please select the chooices you want to operate: ";
	while ((cin >> ch))
	{
		switch (ch)
		{
		case 'A':
		case 'a':
			if (st.isfull())
			{
				cout << "Stack is already full ! " << endl;
			}
			else
			{
				getCustomer(c);
				st.push(c);
			}
			break;
		case 'P':
		case 'p':
			if (st.isempty())
			{
				cout << "Stack is already empty ! " << endl;
			}
			else
			{
				st.pop(c);
				payment += c.payment;
				cout << "customer # " << c.fullname << "'s payment is :" << c.payment << endl;
			}
			break;
		case 'Q':
		case 'q':
			exit(EXIT_FAILURE);
			break;
		default:
			cout << "Please check whether you enter A(a), P(p), or Q(q) again \n";
		}
		cout << "Choose your operation again:";
	}
	cout << "done." << endl;
	return 0;
}

void getCustomer(customer &c)
{
	cout << "Enter the customer's fullname : ";
	getchar();
	cin.getline(c.fullname, 35);
	cout << "Enter the customer's payment : ";
	cin >> c.payment;
}

practice make perfect !

猜你喜欢

转载自blog.csdn.net/qq_37172182/article/details/84076011
今日推荐