#include <iostream>
#include <cctype>
usingnamespace std;
template <class T> //Template for a stack
class Stack //This is a stack class
{
public:
Stack(int); //default constuctor, passed a int variable for size
T pop(); //pop function
void push (T element); //push function
int isEmpty(); //checks if stack is empty
int currSize(); //returns the current size
int isFull(); //checks if stack is full
private:
int size; //holds size of stack
int top; //index of the top location of stack
T *s_ptr; //pointer holds a spot in memory
};
template <class T> //Template constructor
Stack<T> :: Stack(int maxsize) //passed maxsize from initial declaration of stack
{
size = maxsize; //sets private size variable equal to size passed from declaration at main
top = -1; //initially there is no top, so set to -1
s_ptr = new T[size]; //dynamically allocates memory to where pointer was stationed
}
template <class T> //Template push function
void Stack<T> :: push (T element) //passed an element to push
{
if (!isFull()) //if isFull function is not true (not full)
{
s_ptr[++top] = element; //go to next location and put the element in there
}
else
{
cout << "Stack is full!" << endl;
}
}
template <class T> //Template pop function
T Stack<T> :: pop ()
{
if (!isEmpty()) // if isEmpty function is not true (not empty)
{
return s_ptr[top--]; // return the top location and then decrement top by 1
}
else
{
cout << "Stack is empty!" << endl;
}
}
template <class T> //Template isFull function
int Stack<T> :: isFull()
{
if (top == size - 1)
{
return 1;
}
else
{
return 0;
}
}
template <class T> //Template isEmpty function
int Stack<T> :: isEmpty()
{
if (top == -1)
{
return 1;
}
else
{
return 0;
}
}
template <class T> //Template currSize function
int Stack<T> :: currSize ()
{
return (top+1); //returns the actual size of stack at the point it is called
}
int main()
{
Stack <int> nums(100);//declares a stack of ints called "nums".. max 100 spots
int input;
cout << "Enter some numbers, separated by spaces and they will be reversed." << endl << endl;
cin >> input;
while (isdigit(input))
{
nums.push(input);
}
while (!nums.isEmpty())
{
cout << nums.pop();
}
return 0;
}
Can anyone tell me why this doesn't work. It doesn't input into the stack. I'm looping around the condition that the input is a digit.
there are a several issues with the code but for your question as to why it doesn't input into the stack a simple run in gcc debugger shows that that you never get to the inside of
1 2 3 4
while (isdigit(input))
{
nums.push(input);
}
loop so obviously it isn't getting inserted.
It isnt getting into the the loop becuase of your usage of isdigit. its normally not used the way you are trying to use it. not to mention that you are reading your input in as an int so even if it was a char it would be stored as an int so it doesnt really make sense anyways.