Suppose we have some contacts in a file, like a small phone book.
I want to make a small programme that works like an online phone book each contact in the text takes the size of a Line
and, the order that the Information is placed looks like this : NAME SURNAME ADRESS PHONE
, but the Number of phones that each contact has can be more then one. so for example :
George Mikels "green str" 123123 12121232
Maria Luis "olive str" 6548845
In my attempt I have done this so far:
void Createtree(node **head_node)
{
int count=0,*phones;
char filename[50], name[30], surname[50], adress[70];
char c;
FILE *fp;
printf("PLease enter the name of the file\n");
scanf("%s", &filename);
fp = fopen("text.txt", "r");
if(fp == NULL)
{
printf("failed to open file");
return ;
}
do
{
c=fscanf(fp, "%s %s %s ", &name, &surname, &adress);
//takes the name ,surname and adress
printf(" %s %s %s\n", &name, &surname, &adress);
phones = (int*)malloc(sizeof(int));
//creates a dynamic array of int in order to save the phones
do
{
//saves each Number inside the array
c = fscanf(fp, " %d ", phones[count]);
count = count + 1;
phones = (int*)realloc(phones, (count +1) * sizeof(int));
// increases the size of the array in order to save all the phones
}while(c != '\n');
//does it until the end of the Line
count=0;
Insert(head_node,name,surname,phones);
//uses a function to add the Information to a list
}while(c != EOF);
};
I can't save the phones inside the array and I don't know why.
Try allocating the array before the reading and then the actual reading would initialize array's elements.
// define max number size
int maxSizeOfNumber = 20;
// allocate dynamic memory
int *phones = malloc(maxSizeOfNumber * sizeof(int));
// read phone number
do {
c = fscanf(fp, "%d", &phones[count]);
count++;
} while (c > 0 && count < maxSizeOfNumber );
I would advice you to store phone numbers either in character array or string to avoid numbers that would not be stored in an int
, for example those starting with 0
's, as mentioned in the comment section by @Bob__.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.