#include <stdio.h>
#define MAXLEN 100
typedef struct
{
char element[MAXLEN];
int top;
} stack;
stack init(stack s)
{
s.top=-1;
return s;
}
int isEmpty(stack s){
return(s.top==-1);
}
int isFull(stack s){
return (s.top==MAXLEN-1);
}
stack push(stack s,char ch){
if(s.top==MAXLEN-1){
printf("\n the stack is full\n");
return s;
}
else{
++s.top;
s.element[s.top]=ch;
return s;
}
}
stack pop(stack s){
if(s.top==-1){
printf("\n the stack is empty");
return s;
}
else{
--s.top;
return s;
}
}
void top(stack s){
if(s.top==-1){
printf("\n empty stack");
}
else
printf("%c",s.element[s.top]);
}
void print(stack s){
int i;
printf(" serial no character ");
for(i=0;i<s.top;++i){
printf(" %d %c \n",i,s.element[i]);
}
}
int main(){
stack s;
s.top=-1;
init(s);
char e;
int n,j=1,k;
while(j==1){
printf("\n enter your choice 1.push 2.pop 3.top 4.print 5.exit:");
scanf("%d",&n);
switch(n)
{
case 1:
printf("\n enter the element to be pushed: ");
scanf("%ch",&e);
s=push(s,e);
break;
case 2:
s=pop(s);
break;
case 3:
top(s);
break;
case 4:
print(s);
break;
case 5:
j=0;
break;
default:
printf("\n wrong choice entered enter correct one ");
break;
}
}
}
The error occurs after I compiled and run it and have scanned a character; it goes out of the switch and is not scanning the value of n
for consecutive time and is just going into switch with the pre-assigned value and it comes out of switch and asks for n
to enter t. In this way I am encountering space as character automatically in the stack elements and the top is getting doubled. Please help me with this. You can once compile it and check for yourself.