【C++ Primer Plus习题】10.5

问题:

这里是引用

解答:
main.cpp

#include <iostream>
#include "Stack.h"
using namespace std;

int main()
{
	Stack stack;
	customer cust;
	double sum_payment = 0;
	char select;
	cout << "a:入栈 p:出栈 q:退出";
	while (cin.get(select)&&select!='q')
	{
		while (cin.get() != '\n')continue;
		if (select == 'a')
		{
			cout << "请输入顾客的名字:";
			cin.getline(cust.fullname, 35);
			cout << "请输入顾客的支付:";
			cin >> cust.payment;
			while (cin.get() != '\n')continue;
			stack.push(cust);
		}
		if (select == 'p')
		{
			stack.pop(cust);
			sum_payment += cust.payment;
			cout << "出栈的顾客姓名:" << cust.fullname << endl;
			cout << "出栈的支付:" << cust.payment << endl;
			cout << "当前总支付为:" << sum_payment << endl;
		}
		cout << "a:入栈 p:出栈 q:退出";
	}
	cout << "Bye!" << endl;

	return 0;
}

Stack.h

#pragma once

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

typedef customer Item;

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


Stack.cpp

#include "Stack.h"
#include <iostream>
using namespace std;

Stack::Stack()
{
	this->top = 0;
}
bool Stack::isempty()const
{
	return this->top == 0;
}
bool Stack::isfull()const
{
	return this->top == MAX;
}
bool Stack::push(const Item& item)
{
	if (this->isfull())
	{
		cout << "栈已满,无法入栈!" << endl;
		return false;
	}
	this->items[top++] = item;
	return true;
}
bool Stack::pop(Item& item)
{
	if (this->isempty())
	{
		cout << "栈为空,无法出栈!" << endl;
		return false;
	}
	item = this->items[--top];
	return true;
}

运行结果:
在这里插入图片描述

考查点:

  • 数据结构栈
  • 重类型定义typedef

2024年9月4日15:58:36

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值