Reputation: 67
I have created a function that would add books to a structure but when I try to add more books, the previous book is deleted. What is it that I'm doing wrong?
void addBooks(void)
{
char chChoice;
int cnt = 0;
printf("\n\t\t~~ADD NEW BOOK\n");
printf("Enter the isbn: ");
scanf("%d", &b[cnt].nid);
printf("Enter books title: ");
scanf("%s", b[cnt].chTitle);
printf("The record was saved successfully!");
printf("Save more books? (Y / N) ");
scanf("%s", &chChoice);
if (chChoice == 'y')
{
addBooks();
cnt = cnt + 1;
}
else
mainMenu();
}
Upvotes: 0
Views: 56
Reputation: 520
Each time addBooks() is called the value of cnt is reset to zero by the fourth line in your code. Replace that line with:
static int cnt = 0;
This will cause the value to be set to zero only on the first call of addBooks().
In addition you must increment the value of cnt before you recursively call addBooks() like so:
if (chChoice == 'y')
{
cnt = cnt + 1;
addBooks();
}
Upvotes: 1
Reputation: 20244
void addBooks(int cnt) //parameter
{
char chChoice;
// int cnt = 0;
printf("\n\t\t~~ADD NEW BOOK\n");
printf("Enter the isbn: ");
scanf("%d", &b[cnt].nid);
printf("Enter books title: ");
scanf("%s", b[cnt].chTitle);
printf("The record was saved successfully!");
printf("Save more books? (Y / N) ");
scanf(" %c", &chChoice);
if (chChoice == 'y')
{
addBooks(cnt+1);
}
else
mainMenu();
}
You need cnt
as a parameter else as cnt
is local,you reset the value to 0 itself. You could also declare cnt
as static
and if you do so,don't forget to increment cnt
before calling your function. Also,use %c
for a character and not %s
.
Upvotes: 1