题目:
考虑下面的结构声明
struct customer {
char fullname[35];
double payment;
};
编写一个程序,它从栈中添加和删除customer结构(栈用Stack类声明)。每次customer结构被删除时,其payment的值都被添加到总数中,并报告总数。
源代码:
test.h
#ifndef STACK_H_
#define STACK_H_
typedef struct customer {
char fullname[35];
double payment;
}Item;
class Stack
{
private:
enum {MAX = 10};
Item items[MAX];
int total;
int top;
public:
Stack();
bool isempty() const;
bool isfull() const;
bool push(const Item& item);
int pop(Item& item);
};
#endif
test.cpp
#include "test.h"
#include <iostream>
#include <cctype>
int main()
{
using namespace std;
Stack st;
char ch;
Item po;
cout << "Please enter A to add a purchase order,\n"
<< "P to process a PO, or Q to quit.\n";
while (cin >> ch && toupper(ch) != 'Q')
{
while (cin.get() != '\n')
continue;
if (!isalpha(ch))
{
cout << '\a';
continue;
}
switch (ch)
{
case 'A':
case 'a':
cout << "请输入fullname: ";
cin.getline(po.fullname, 35);
cout << "请输入payment: ";
(cin >> po.payment).get();
if (st.isfull())
cout << "stack already full\n";
else
st.push(po);
break;
case 'P':
case 'p':
if (st.isempty())
cout << "stack already empty\n";
else
{
cout << "payment总数:" << st.pop(po) << endl;;
}
break;
}
cout << "Please enter A to add a purchase order,\n"
<< "P to process a PO,or Q to quit.\n";
}
cout << "Bye\n";
return 0;
}
test_function.cpp
#include "test.h"
Stack::Stack()
{
top = 0;
total = 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;
}
int Stack::pop(Item& item)
{
if (top > 0)
{
item = items[--top];
return total += item.payment;
}
else
{
return 0;
}
}
演示效果:
如果朋友你感觉文章的内容对你有帮助,可以点赞,关注文章和专栏以及关注我哈,嘿嘿嘿我会定期更新文章的,谢谢朋友你的支持哈
标签:const,Item,top,练习,C++,item,67,return,Stack From: https://blog.csdn.net/little_startoo/article/details/143480958