c - creating a stack using arrays -


i'm trying write code creatin' stack usin' array, i'm suppposed use dynamic memory allocation. problem it's not takin' scannin' response determines whether should exit loop.

#include<stdio.h>  static int top, size, *a, x;  stfull(){     if(top<size) x = 0;     else x = 1; }  stempty(){     if(!top) x = 1;     else x = 0; }  push(int z){     if(x){         printf("stack full\tstack overflow\n");         return;     }     else{         a[top] = z;         top++;         return;     } }  pop(){     if(x){         printf("empty stack\tstack underflow\n");         return;     }     else{         printf("%d  ", a[top]);         top--;         return;     } }  main(){     int num, res;     char ans = 'y';      printf("array size:\t");     scanf("%d", &size);      = malloc(size*sizeof(int));      printf("choose number result\n1. push elements\n2.display elements\n3.exit\n");     scanf("%d", &res);      switch(res){         case 1:              while(ans == 'y'){                 printf("enter number\t");                 scanf("%d", &num);                  push(num);                  printf("enter more?\t");                 ans = getchar();             }            break;         case 2:             do{                 pop();                  printf("pop more?\t");                 ans = getchar();             }while(ans == 'y');         break;         case 3:              exit(1);     } } 

sample input:

array size: 5

choose number result

1. push elements

2.display elements

3.exit
1

enter number 3

enter more?

the program exits after point irrespective of value of ans. can correct code?

your code exits because getchar() reads \n [enter] pressed character ans.
input

enter number 3[enter] 

so

ans=getchar(); 

reads [enter]. 1 easy solution use getchar() twice as

getchar(); ans=getchar(); 

your code continue working


Comments

Popular posts from this blog

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -

ruby on rails - In a controller spec, how to find a specific tag in the generated view? -