Re: another question about entering names in a queue
elodie wrote:
Hi everyone,
I am working on the piece of code below. It is supposed to allow the
user to insert 10 or so names into a queue, and do other operations,
such as deletion of a name, and print the queue.
When I scan several names successively, and then print the queue, the
name I entered first is not printed. The name I entered second is
printed first, and so on. I am not sure if the name I entered first is
not scanned, or not printed, or lost somewhere along the way. I would
appreciate your suggestions on how to identify and solve this issue.
Thanks a lot in advance for your help.
#include <stdio.h>
#include <string.h>
#define MAXNUM 10
#define MAXS 8
My name might fit in 8 chars, but what about those that are longer?
void insertq(void);
void deleteq(void);
void insertq(void);
void printq(void);
char q[MAXNUM][MAXS];
int h, t;
void main(void)
int main(void)
{
char response[MAXS];
Uninitialized array. Consider
char response[MAXS] = {0};
h=-1;
t=-1;
printf("i/d/p/q");
scanf("%s", response);
Extremely dangerous. What if I type more than MAXS-1 characters?
while (response[0] != 'q' && response[0] != 'Q')
switch(response[0]){
case 'i':
insertq();
break;
case 'd':
deleteq();
break;
case 'p':
printq();
break;
default:
printf("error input i/p/d/q");
break;
}
printf("i/p/d/q");
scanf("%s", response);
}
void insertq(void)
{
char response[MAXS];
if (t-h+1 == MAXNUM)
printf("overflow \n");
else{
printf("enter name");
scanf("%s", response);
strcpy(q[++t],response);
if(h==-1){
h=0;
t=-1;
So, you're resetting 't' here? Why?
}
}
}
void printq(void)
{
char response[MAXS];
int j;
printf("l or p");
scanf("%s", response);
if(response[0]=='l')
for (j=h; j<=t; j++)
printf("%d %s \n", j, q[j]);
if (response[0]=='p')
for (j=h; j<=MAXNUM; j++)
printf("%d %s \n", j, q[j]);
}
void deleteq(void)
{
if(h==-1)
printf("underflow \n");
else
printf("servicing %s \n", q[h++]);
if(h>t){
h=-1;
t=-1;
}
}
Have you tried stepping through your program at least a couple of times
with a pencil and paper? Or perhaps using the debugger?
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask