I am writing a stacks program that is menu driven. The user has 4 options (Push, Pop, Print and Quit). I'm not certain all of my code is right yet and may require additional tweeking, but the problem I am encounting right now is with the menu.
When I run the program the menu displays and when I enter a selection, the menu displays again and does not do anything based on my selection. I can enter any selection number and the menu simply displays again... Help is appreciated! Thank you!
MAIN.C
Code:
#include <stdio.h>
#include "boolean.h"
#include "stack.h"
int main(void) {
char choice;
boolean quit = 0;
int data_item;
int data_popped;
stack top;
init_stack(&top);
while (quit == 0){
printf("1 Push\n");
printf("2 Pop\n");
printf("3 Print\n");
printf("4 Quit\n\n");
printf("Enter Selection: ");
scanf(" %c", &choice);
printf("\n");
}
switch (choice){
case '1':
if (!is_full()) {
printf("Enter the data\n");
scanf("%d", &data_item);
push (&top, data_item);
}
else {
printf("The Stack is Full\n");
}
break;
case '2':
if (!is_empty(top)) {
data_popped = pop(&top);
printf("&d was removed", data_popped);
}
else {
printf("The Stack is Empty\n");
}
break;
case '3':
if (!is_empty(top)){
print_stack(top);
}
else {
printf("The Stack is Empty\n");
}
break;
case '4':
if(quit == 0){
quit = 1;
}
break;
default:
printf("Invalid Selection\n");
break;
}
}
STACK.C
Code:
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
void init_stack(stack *s) {
(*s) = NULL;
}
boolean is_full(void) {
stack temp;
temp = (stack) malloc (sizeof(struct stacknode));
if (temp == NULL)
return TRUE;
else {
free (temp);
return FALSE;
}
}
boolean is_empty(stack s) {
if (s == NULL)
return TRUE;
else
return FALSE;
}
void push(stack *s, int x){
stack temp;
temp = (stack) malloc(sizeof(struct stacknode));
temp -> data = x;
temp -> next = (*s);
(*s) = temp;
}
int pop(stack *s) {
stack temp;
int data_popped;
temp = *s;
data_popped = temp -> data;
*s = temp -> next;
free (temp);
return data_popped;
}
void print_stack(stack s) {
if (!is_empty(s)) {
printf("%d\n", s->data);
print_stack(s->next);
}
}
STACK.H
Code:
#ifndef STACK_H
#define STACK_H
typedef struct stacknode{
int data;
struct stacknode *next;
} *stack;
typedef int boolean;
#define TRUE 1
#define FALSE 0
void init_stack(stack *);
boolean is_full(void);
boolean is_empty(stack);
void push(stack *, int);
int pop(stack *);
#endif
BOOLEAN.H
Code:
#ifndef BOOLEAN_H
#define BOOLEAN_H
typedef int boolean;
const boolean FALSE = 0;
const boolean TRUE = 1;
#endif