I have to make a library system using structs and pointers, that registers a person with their name, ID, phone number, and the name of the books (maximum 3). I have created a struct for every borrower, and I am trying to store input taken by the user, specifically at the part of getting the book titles, to store into an array of other structs (for other borrowers). I have to be able to free the locations of the borrowers once they return all books, so I'd have to use dynamic memory for that.
This is the code I have so far, not sure how exactly I would go about storing every borrower using pointers.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_NAME_SZ 256
#define CLEAR() system("CLS")
struct borrower
{
char name[20];
char lastName[20];
char id[7];
char phoneNumber[10];
char titleOfBook[3][20];
};
int main(void)
{
struct borrower b;
char op;
do
{
puts("\n1) Register borrower");
puts("2) Find by ID");
puts("3) Show All");
puts("4) Erase by ID");
puts("0) Exit");
printf("Option:");
setbuf(stdin, 0);
opc=getchar();
switch(op)
{
case '1':
RegisterBorrower(&b);
break;
case '2':
//showID();
break;
case '3':
//showAll();
break;
case '4':
//erase();
break;
case '0':
break;
}
}while (op!=48);
return 0;
}
void RegisterBorrower(struct borrower *b)
{
CLEAR();
setbuf(stdin,0);
printf("ID: "); gets(p->id);
printf("Name: "); gets(p->name);
printf("Last Name: "); gets(p->lastName);
setbuf(stdin,0);
printf("Phone Number: "); gets(p->phoneNumber);
int numberOfBooks=0, cont=0, i;
char bookTitle[20];
printf("How many books do you want to take out?(max 3): ");
scanf("%d", &numberOfBooks);
setbuf(stdin,0);
if(numberOfBooks<=3 && numberOfBooks>0)
{
for(i=0; i<numberOfBooks; i++)
{
setbuf(stdin,0);
printf("Book Title: "); gets(bookTitle);
strcpy(p->titleOfBook[i][0], bookTitle);
}
}else
{
printf("You cannot take out this amount of books.");
}
}
Everything "works" (doesn't crash) up until the part I ask for the book titles, it only runs once. Any help would be greatly appreciated.
EDIT: My problem was that I used
strcpy(p->titleOfBook[i][0], bookTitle);
which only copies to one character because of the [0]. I changed it to
strcpy(p->titleOfBook[i], bookTitle);
and it worked fine.