Hi all,
I'm trying to write a program that handles a queue. It works when I add an element to the queue (push), but not when I use the command pop(). The program doesn't seem to go into the function. When I write pop, the program just jumps to the next row in the command prompt and seems to be waiting for some new input. If I write pop a second time it looks like its working. Anyone can help me out? Thanks a lot!
Below is the code.
Code:
// A queue system
// Enter push a, for example to put the new char a in queue
// Enter pop to retrieve first element in queue
#include <stdio.h>
#define MAX 200
void push(char c); // Puts a new element last in queue
char pop(void); // Gets the first element in queue
int compare_str(char a[], char b[]);
static char s[MAX];
int first = -1;
int last = -1;
int main(void)
{
char c, cpop, cont = 'y';
char command[4];
int result, i;
printf("Enter push character to put a new element in in queue. Enter pop to retrieve firs element in queue:\n");
while(cont == 'y')
{
scanf(" %s %c", command, &c); // space between %s and %c to get rid of spaces
// Get command
result = compare_str(command, "push");
printf("result: %d\n", result);
if(result == 0)
push(c);
result = compare_str(command, "pop");
printf("result: %d\n", result);
if(result == 0)
{
cpop = pop();
printf("%c was withdrawn\n", cpop);
}
printf("Queue is now: \n");
i = 0;
while(s[i] != '\0')
{
printf("%c ", s[i]);
i++;
}
printf("\nContinue? (y/n) ");
scanf(" %c", &cont);
printf("\ncontinue: %c\n", cont);
}
return 0;
}
int compare_str(char a[], char b[])
{
int c = 0;
while(a[c] == b[c])
{
if(a[c] == '\0' || b[c] == '\0')
break;
c++;
}
if(a[c] == '\0' && b[c] == '\0')
return 0;
else
return -1;
}
void push(char c)
{
last++;
s[last] = c;
printf("Inside push()\n");
}
char pop(void)
{
first++;
return s[first];
printf("Inside pop()\n");
}