Reputation: 21
I am trying to implement a basic stack in array using templates. Based on user input, Preferred stack type is formed. But while compiling, It gives an error "s was not declared in this scope" after checking stack_type in the if condition. If condition check is commented, It is not showing any error. Would someone mind explaining why am getting this error??
#include<iostream>
using namespace std;
template < class Typ, int MaxStack >
class Stack {
Typ items[MaxStack];
int EmptyStack;
int top;
public:
Stack();
~Stack();
void push(Typ);
Typ pop();
int empty();
int full();
};
template < class Typ, int MaxStack >
Stack< Typ, MaxStack >::Stack() {
EmptyStack = -1;
top = EmptyStack;
}
template < class Typ, int MaxStack >
Stack< Typ, MaxStack >::~Stack() {
delete []items;
}
template < class Typ, int MaxStack >
void Stack< Typ, MaxStack >::push(Typ c) {
items[ ++top ] = c;
}
template < class Typ, int MaxStack >
Typ Stack< Typ, MaxStack >::pop() {
return items[ top-- ];
}
template< class Typ, int MaxStack >
int Stack< Typ, MaxStack >::full() {
return top + 1 == MaxStack;
}
template< class Typ, int MaxStack >
int Stack< Typ, MaxStack >::empty() {
return top == EmptyStack;
}
int main(void) {
int stack_type;
char ch;
cout << "Enter stack type: \n\t1.\tcharater stack\n\t2.\tInteger stack\n\t3.\tFloat stack\n";
cin >> stack_type;
if(stack_type == 1)
Stack<char, 10> s; // 10 chars
/* if(stack_type == 2)
Stack<int, 10> s; // 10 integers
if(stack_type == 3)
Stack<float, 10> s; // 10 double*/
while ((ch = cin.get()) != '\n')
if (!s.full())
s.push(ch);
while (!s.empty())
cout << s.pop();
cout << endl;
return 0;
}
Upvotes: 1
Views: 36
Reputation: 206697
if(stack_type == 1)
Stack<char, 10> s; // 10 chars
is equivalent to:
if(stack_type == 1)
{
Stack<char, 10> s; // 10 chars
}
s
is, of course, not in scope in the following line.
I am unable to suggest a fix since you haven't explained what you are hoping to accomplish in your program.
Upvotes: 2