#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
#define DataType char
typedef struct ArrayQueue {
int front;
int rear;
DataType queue[MAX_SIZE];
} } ArrayQueue;
void init_queue(ArrayQueue *AQ){ // Queue initialization
AQ->front = AQ->rear = 0;
}
intis_queue_full(ArrayQueue *AQ){ // Determine if the queue is saturated
return ((AQ->rear + 1) % MAX_SIZE) == AQ->front;
}
intis_queue_empty(ArrayQueue *AQ){ // Determine if the queue is blank
return AQ->front == AQ->rear;
}
void queue (ArrayQueue *AQ, DataType data) { // Insert into queue
if (is_queue_full(AQ)){
printf("Insertable\n");
exit(1);
}
else {
int len = strlen(data);
AQ->rear = (AQ->rear + len) % MAX_SIZE;
AQ->queue[AQ->rear] = data;
}
}
void print_queue(ArrayQueue *AQ){ // Output queue items
printf("front->");
int i;
for(i = AQ->front; i != AQ->rear; ){
i = (i+1) % MAX_SIZE;
printf("%d ", AQ->queue[i]);
}
printf("\n");
}
main(){
ArrayQueue male, female;
init_queue(&male);
init_queue(&female);
char name[MAX_SIZE];
char gender;
printf ("Customer Name: ");
scanf("%s", name);
printf("Please enter a star (form):");
scanf(" %c", &gender);
if(strcmp(gender, 'm'))
enqueue(&male, name);
else if(strcmp(gender, 'f'))
enqueue(&female, name);
print_queue(&male);
}
I'm asking you a question because I bumped into the wall during the assignment. I would like to receive the customer's name and gender and save the name in the queue called male if the gender is male and female if the gender is female if the gender is male.
After writing the code, I entered the customer name "Hong Gil-dong" and gender "m" as a test, and tried to print out the stored queue male using print_queue, but it did not print out.
There seems to be a problem with the enqueue part. First, after declaring an integer variable called len, the length of the data (name) was stored using strlen, then the rear was moved using len, and the data was entered.
intlen = strlen(data);
AQ->rear = (AQ->rear + len) % MAX_SIZE;
AQ->queue[AQ->rear] = data;
The problem I think is AQ->queue[AQ->rear] = data; If you position the data you entered in this part as AQ->queue[AQ->area], the data you entered is not stored in a single location, AQ->queue[AQ->area], because it is a string.
Therefore, the code of the enqueue part is also
AQ->rear= (AQ->rear+1)% MAX_SIZE;
AQ->queue[AQ->rear] = data;
I tried switching to and typing the name in a single letter, but the result was the same.
I want to know what is wrong with the code.
c queue
queue
is char[100]
data. The intention is that queue[i]
should be char[100]
.
When queue[i]
copies the string, you will need to copy it using strcpy
.
© 2024 OneMinuteCode. All rights reserved.