I am a student and one of our homework's tasks is to write a program on C that has 2 structures: One for family one for person(shown below). We are supposed to get the family members info including name and ID and later print it, using dynamic allocation for the name field(in the person's structure).
Heres my code, but something goes wrong with it.It does not let me proceed with the mother's details...I mean, It skips the part where you need to insert the name, goes directly to "ID". I tried to add "flushall" but it doesnt seem to work. There might be more problems with the code that I am not aware of yet, since I'm still trying to figure out whats wrong with this one:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Person {
char* name;
long id;
}person;
typedef struct Family {
person dad;
person mom;
int numOfKids;
person* pointers[10];
}family;
void readDate(person* t);
void printData(person* t);
void readFamily(family* f);
void printFamily(family* f);
void main()
{
family ff;
readFamily(&ff);
printFamily(&ff);
free(ff.dad.name);
free(ff.mom.name);
for (int i = 0; i < ff.numOfKids; i++)
free(ff.pointers[i]->name);
}
void readDate(person* t)
{
int size;
char names[200];
printf("Please enter a name\n");
_flushall;
gets_s(names);
size = strlen(names);
t->name = (char*)calloc(1, sizeof(names + 1));
t->name = names;
printf("Please enter ID\n");
scanf("%d", &t->id);
}
void printData(person* t)
{
printf("%s %d\n", t->name, t->id);
}
void readFamily(family* f)
{
(f->numOfKids) = 0;
int countinue = 1;
char c;
printf("Please enter the father's info\n");
_flushall;
readDate(&(f->dad));
printf("Please enter the mother's info\n");
_flushall;
readDate(&(f->mom));
do {
printf("Would u like to add a child? Y/N\n");
_flushall;
scanf("%c", &c);
if (c == 'N' || c == 'n')
{
countinue = 0;
}
else
{
printf("Pleae enter the child's info:\n");
readDate((f->pointers[f->numOfKids]));
f->numOfKids++;
}
} while (countinue &&f->numOfKids <= 10);
}
void printFamily(family* f)
{
printf("The family's parents info:\n");
printf("Mom:%s ID:%d\t Dad:%s ID:%d\n", f->mom.name, f->mom.id, f->dad.name, f->dad.id);
if (f->numOfKids == 0)
printf("There are no children!\n");
else
{
for (int i = 0; i < f->numOfKids; i++)
{
printf("#%d:Name:%s ID:%d\n", i + 1, f->pointers[i]->name, f->pointers[i]->id);
}
}
printf("\n");
}