在受到我的实验室教练的启发后,我做了这件小事。我的程序可以很好地完成弹出,但是在最后的推动下它失败了。该值在超过阵列阈值后消失。有没有办法阻止它?
我们将不胜感激。谢谢:))
此外,由于必须使用3个全局变量,我现在正在面对自己。正确方向的某些方面会有所帮助。
#include<iostream>
#include<cstdlib>
#include<conio.h>
using namespace std;
int n, *stack, *slack;
class stacks
{
int position;
public:
stacks()
{
stack = new int[n];
slack = new int[n];
for(int i=0;i<n;i++)
stack[i]='\0';
position = 0;
}
void insert()
{
push();
position--;
system("cls");
cout<<"Enter the number to be added: ";
cin>>stack[0];
position++;
}
void push()
{
system("cls");
cout<<"The stack has been pushed";
slack[0]=0;
for(int j=0; j<n-1;j++)
{
slack[j+1]=stack[j];
}
for(int j=0; j<n;j++)
{
stack[j] = slack[j];
}
position++;
stack[0] = 0;
}
void pop()
{ system("cls");
int i=0;
if(position<1)
{
cout<<"Underflow!";
return;
}
cout<<"The number has been successfully popped from the stack!";
while(stack[i] != '\0')
{
stack[i]=slack[i];
i++;
}
for(int j = 0 ; j<i ; j++)
{
stack[j]=stack[j+1];
}
stack[i] = '\0';
position--;
}
void memusage()
{
system("cls");
cout<<"The total memory usage is: "<<position+1<<"/"<<n<<" .";
}
void display()
{
for(int j = 0 ; j<n ; j++)
{
cout<<j+1<<" Member is: "<<stack[j]<<endl;
}
}
};
int main()
{
cout<<"Enter the number of elements: ";
cin>>n;
stacks a;
char ac = 'y', b;
while( ac == 'y' || ac =='Y' || ac =='\n')
{
system("cls");
a.display();
cout<<"\n\n\n";
cout<<"Enter a new value [1]"<<endl;
cout<<"Push the stack [2]"<<endl;
cout<<"Pop the stack [3]"<<endl;
cout<<"See memory usage [4]"<<endl;
cout<<"\n\nEnter your choice[1,2,3,4]: ";
b=getch();
if(b=='1')
{a.insert();}
else if(b=='2')
{a.push();}
else if(b=='3')
{a.pop();}
else if(b=='4')
{a.memusage();}
else cout<<"\nInvalid Entry. Please choose a valid entry!\n";
cout<<"\n\nAnother?[y/Y]";
ac=getch();
}
}