首页 > 试题广场 >

考虑下面的结构声明:

[问答题]
考虑下面的结构声明:
struct customer {
      char fullname[35];
      double payment;
};
编写一个程序,它从栈中添加和删除customer结构(栈用Stack类声明表示)。每次customer结构被删除时,其payment的值都被加入到总数中,并报告总数。注意:应该可以直接使用Stack类而不作修改;只需修改typedef声明,使Item的类型为customer,而不是unsigned long即可。
#ifndef STACK_H_
#define STACK_H_
struct custormer
{
    char fullname[35];
    double payment;
};
typedef custormer Item;
class Stack
{
public:
    Stack();
    bool isempty() const;
    bool isfull() const;
    bool push(const Item &item);
    bool pop(Item &item);

private:
    enum {MAX=10};
    Item items[MAX];
    int top;
};
#endif STACK_H_
//以上为头文件
#include <iostream>
#include "stack.h"
using namespace std;
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;
}
int main()
{
	Stack st;
	custormer cust;
	double sum_payment=0;
	char select;
	cout<<"Select a (add),p(pop),q(quit)";
	while (cin.get(select)&&select!='q')
	{
		while(cin.get()!='\n') continue;
		if (select=='a')
		{
			cout<<"Enter a custormer's name:";
			cin.getline(cust.fullname,35);
			cout<<"Enter a custormer payment:";
			cin>>cust.payment;
			while(cin.get()!='\n') continue;
			st.push(cust);
			cout<<"Item pushed"<<endl;
		}
		if (select=='p')
		{
			st.pop(cust);
			sum_payment=cust.payment+sum_payment;
			cout<<"Pop item's info:"<<endl<<"Name:"<<cust.fullname<<endl;
			cout<<"Payment: "<<cust.payment<<endl;
			cout<<"Now,sum of payment:"<<sum_payment<<endl;
		}
		cout<<"Select a (add),p(pop),q(quit)";
	}
	cout<<"Bye"<<endl;
	system("pause");
	return 0;
}

编辑于 2021-03-09 21:35:16 回复(0)