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 !

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值