![](/img/trans.png)
[英]Why I can't get the correct output when moving data from text file to array
[英]i can't get an output from this
#include<iostream>
using namespace std;
class stack
{
int size=10;
int stack[size]={0}, value=0, top;
top=size;
public:
void push(int v)
{
if(top==0)
cout<<"\nstack is full\n";
else
{--top;
stack[top]=v;}
}
void pop()
{
if(top==size)
cout<<"\nstack is empty\n";
else
{top++;
stack[top];
stack[top-1]=0;
}
}
void display()
{
if(top==size)
cout<<"\nstack empty\n";
else
{
for(int i=top;i<size-1;i++)
{
cout<<stack[i];
}
}
}
};
int main()
{
stack s;
char t;
int value,ch;
do
{
cout<<"\n1.push\n";
cout<<"\n2.pop\n";
cout<<"\n3.display\n";
cout<<"enter choice:\n";
cin>>ch;
switch(ch)
{
case 1:cout<<"\nenter the value to be pushed\n";
cin>>value;
s.push(value);
break;
case 2:s.pop();
break;
case 3:s.display();
break;
default:
cout<<"\nwrong choice\n";
}
cout<<"\ndo u want to retry\n";
cin>>t;
}while(t=='y' || t=='Y');
return 0;
}
解决发生的错误的最简单方法是将int size=10;
更改int size=10;
到static const int size=10;
。 此后,除了使用stack[top];
发出警告外stack[top];
如果为空语句,则for(int i=top;i<size-1;i++)
display
循环中存在逻辑错误,应该为for(int i=top;i<size;i++)
或for(int i=top;i<=size-1;i++)
。
正如TomášZahradníček回答的那样,您需要修复一些问题才能编译代码(使用-std = c ++ 11)。
我在display
方法中使用for(int i=top; i<size; ++i)
。 我还补充说,您的pop
方法可以简单地执行top++;
而不覆盖堆栈。
无论如何,关于在cout上不打印任何内容的问题:您显然尝试了将1个项目推入堆栈,但没有尝试将2个项目推入堆栈,这将指出错误的行( for
循环)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.