本文主要是介绍【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 oncestruct 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
这篇关于【C++ Primer Plus习题】10.5的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!