problem description
I want to read out the contents of a text file, but I don"t know why the line read is stored in the char * type of my custom struct type, which always modifies the previous read char *. I marked out the problem with comments
related codes
-sharpdefine _CRT_SECURE_NO_WARNINGS
-sharpinclude<stdio.h>
-sharpinclude<string.h>
-sharpinclude<stdlib.h>
-sharpdefine SIZE 100
-sharpdefine QUEUE_SIZE 100
-sharpdefine TRUE 1
-sharpdefine FALSE 0
typedef int bool;
struct Customer
{
char *name;
int arrivedTime;
int priority;
int age;
int requireTime;
};
struct Queue
{
struct Customer customers[QUEUE_SIZE];
int size;
};
bool addCustomer(struct Queue* queue,struct Customer customer) {
if (queue->size >= QUEUE_SIZE) {
return FALSE;
}
else {
queue->customers[queue->size] = customer;
queue->sizePP;
return TRUE;
}
}
struct Customer getCustomer(struct Queue* queue,int index) {
return queue->customers[index];
for (int i = index; i < queue->size-1; iPP) {
queue->customers[i] = queue->customers[i + 1];
}
queue->size--;
}
int main() {
struct Queue queue;
queue.size = 0;
FILE * file=fopen("C:\\Users\\zjb52\\Desktop\\cs\\sample-input.txt", "r");
if (file == NULL) {
printf("File not found");
}
else {
char buffer[SIZE];
while(fgets(buffer, SIZE, file) != NULL) {
struct Customer customer;
//s1,queues0s1
customer.name = strtok(buffer, " ");
customer.arrivedTime = atoi(strtok(NULL, " "));
customer.priority = atoi(strtok(NULL, " "));
customer.age = atoi(strtok(NULL, " "));
customer.requireTime = atoi(strtok(NULL, " "));
addCustomer(&queue, customer);
}
}
fclose(file);
system("pause");
return 0;
}
sample-input.txt
s0 0 3 0 10
s1 0 6 0 20
s2 0 5 0 11
s3 0 6 0 20
s4 67 2 0 25
s5 5 4 0 1
s6 0 2 0 5
s7 0 4 0 28
s8 0 3 0 20
s9 45 5 0 6
s10 103 3 0 2
what result do you expect? What is the error message actually seen?
customer.name = strtok (buffer, "" in the while loop; what I expect is that after reading, the customer.name in the queue should be s0mems1, s2.s9, S10, but the result is all S10. Why is the char * type name in struct like this? How should I change it? Thank you