5. 考虑下面的结构声明:
struct customer {
char fullname[35];
double payment;
};
编写一个程序,它从栈中添加和删除customer结构(栈用Stack类声明表示)。每次customer结构被删除时,其payment的值都被加入到总数中,并报告总数。注意:应该可以直接使用Stack类而不作修改;只需修改typedef声明,使Item的类型为customer,而不是unsigned long即可。
// stack.h -- struct and class definition
#ifndef STACK_H_
#define STACK_H_
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);
};
#endif
// stack.cpp -- class member functions' definition
//#include "stdafx.h"
#include "stack.h"
Stack::Stack()
{
top = 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;
}
bool Stack::pop(Item& item)
{
if (top > 0)
{
item = items[--top];
return true;
}
else
return false;
}
// stacker.cpp -- check the class and the functions
//#include "stdafx.h"
#include <iostream>
#include "stack.h"
#include <cctype>
using namespace std;
int main()
{
Stack st;//栈“结构”!!!
char ch;
customer temp;
double totalpayment = 0;
cout << "please enter A/a to add a custonmer\n"
<< "D/d to delete a custonmer\n"
<< "Q/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 << "enter the name:";
cin.getline(temp.fullname, 35);
cout << "\nenter the payment:";
cin >> temp.payment;
if (st.isfull())
cout << "stack is fulled!\n";
else {
st.push(temp);
}
break;
case'd':
case 'D':
if (st.isempty())
cout << "stack already empty!\n";
else {
totalpayment += temp.payment;
cout << "\ntotalpayment:" << totalpayment << endl;
st.pop(temp);//为何压出的是temp?怎么确定temp就是最上面的那个?
//在类方法定义中,通过top自加和自减来控制temp始终是添加进去的第一个和弹出时的最上层的!
//但是 怎么实现删除这个步骤的呢? 我还是没懂!
cout << "the information of " << temp.fullname << " has been deleted!\n";
}
break;
}
cout << "please enter A/a to add a custonmer\n"
<< "D/d to delete a custonmer\n"
<< "Q/q to quit!\n";
}
cout << "Service end.\nThe total payment is " << totalpayment << endl; cout << "Bye!\n";
system("pause");
return 0;
}