Hi everyone, I had a question regarding my current program. I have just about completed it but have noticed a small error. In my peek function, I want the program to look through the entire stack for the number 5, but I've noticed that it only looks to the very last number (not counting a number greater then 9).
For instance if I enter (1,2,3,4,5) it will return stating that the number 5 is in the stack
but
if I enter (5,4,3,2,1) it will return stating that the number 5 is not in the stack when it obviously is. I've looked over the program a few times and cannot see where I went wrong because every change I've tried to make so far has produced an error.
Please help
Any help would greatly be appreciated
Thanks
Code:#include <iostream.h> //This is my preprocessor directive for the cout/cin statements//
const int Stack_Size=10; //Initialization of Stack Size//
class Stack
{
public:
Stack(); //constructor//
void push(int);
int pop();
bool peek();
bool empty();
bool full();
private:
int count;
int data[Stack_Size];
};
Stack::Stack()
{
count=-1;
}
void Stack::push(int value)
{
count++;
data[count]=value;
}
int Stack::pop()
{
int topvalue;
topvalue=data[count];
count--;
return(topvalue);
}
bool Stack::peek()
{
if (data[count]==5) //If 5 is within the stack this function will return 1 (true)
return 1;
else //else it will return 0 (false)
return 0;
}
bool Stack::empty()
{
if (count==-1) //If the stack is empty this function will return 1 (true)
return 1;
else
return 0;
}
bool Stack::full()
{
if (count==Stack_Size-1)
return 1;
else
return 0;
}
int main()
{
Stack entries;
int number;
char answer;
cout<<" Please enter as many digits as you wish.\n If you wish to end your entries, please enter a number greater than 10\n ";
while(1)
{
cout<<"Digit:\n";
cin>>number;
if (number>9) //If the entry is >9, the loop will break and that number will not count in the stack//
break;
if (entries.full())
{
cout<<"The stack is full and you do not have any space left\n";
break;
}
else
entries.push(number);
}
cout<<"Is value 5 in the stack (peek): ?\n";
if (entries.peek())
{
cout<<"This stack does contain value 5\n";
}
else
cout<<" This stack does not contain value 5\n";
if (entries.empty())
{
cout<<"The stack is empty\n";
}
else
while (!entries.empty())
{
cout<<" Do you want to pop an item from the stack? ";
cin>>answer;
if (answer=='y')
cout<<entries.pop()<<endl;
else
break;
}
return 0;
}