Stack 函数问题

Mr.chan ?? ?? 2020-04-09 09:20:21
如果判断堆栈是否满了。下面的是我代码,还有就是“stack is full”这句话为什么不管怎么样都会打印出来。请教大神。
#include <iostream>

#include "iomanip"
#include<string>
#include <cmath>
using namespace std;


class Stack{
private:
char *arr;
int top;
int capacity;
int size;
public:
Stack(){
int size = 5;
arr = new char[size];
top = -1;
capacity = size;
}
bool isEmpty()
{
if(top == -1)
return true;
return false;
}

void push(char line)
{
if(top == size - 1)
cout<<"Stack is full"<<endl;
arr[++top] = line;
}
void pop()
{
if(!isEmpty())
top--;
}
char peek()
{
if(!isEmpty())
return arr[top];
return '0';
}
};

int main(){
string line;
Stack stack;
cout<<"Enter a string: "<<endl;
cin>>line;
for(int i = 0; i<line.length();i++)
{
stack.push(line[i]);
}
while(!stack.isEmpty())
{

cout<<stack.peek();
stack.pop();
}
return 0;
}


...全文
105 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Mr.chan ?? ?? 2020-04-09
  • 打赏
  • 举报
回复
还有一个问题就是。例如我输入happy。输出的应该是yppah。但是如果我输入happyy 六个字符。那么他只是打印了那句话,六个字符已经超过size的范围。不是不能插入吗?
真相重于对错 2020-04-09
  • 打赏
  • 举报
回复
Stack(){ size = 5; arr = new char[size]; top = -1; capacity = size; } 注意红字

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧