hi
i want To Write a PhonBook program in c which will accept a Name and a Number from the User an save them in a struct, the problem is how to create a new structure name every time :
here is the could , though its not work but it will clear i what i mean .

#include <stdio.h>
#include <stdlib.h>

struct PhoneBook
{
    char FullName[50];
    long PhoneNumber;

};

void get_id()
{
    char Name[50];
    long Number;
    printf("Please Enter A Label for The Contact:\n");
    scanf("%s",&Name);
    struct PhoneBook Name;
    printf("please Enter The Name of the Contact :\n");
    gets(Name.FullName);
    printf("Enter The Phone Number :\n");
    scanf("%d", &Name.PhoneNumber);;
    printf("The Phone Number of %s Save as %d", Name.FullName, Name.PhoneNumber);
}


void main()
{
    get_id();
}

for example i dont what to write the name of the contact manuale like :
struct PhoneBook John
struct Phonebook Eli
and Then use them , i just what them to be created automaticaly as the user enters the name .

You need a data structure that can hold anonymous (unnamed) objects of the struct. For an unknown number of records, I'd suggest a linked list. Here's something to get you started:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct record
{
    char *name;
};

struct node
{
    struct record data;
    struct node *next;
};

static struct node *list = NULL;

int main(void)
{
    struct node *temp;
    char line[BUFSIZ];

    // Build the list from user input
    while (1)
    {
        fputs("Name: ", stdout);

        if (fgets(line, sizeof line, stdin) != NULL)
        {
            // Clean up the newline character
            line[strcspn(line, "\n")] = '\0';

            if (line[0] == '\0')
            {
                // A blank name stops input
                break;
            }

            temp = malloc(sizeof *temp);

            if (temp != NULL)
            {
                // Populate the record and prepend it to the list
                temp->data.name = _strdup(line);
                temp->next = list;
                list = temp;
            }
            else
            {
                perror("Error creating record");
            }
        }
        else
        {
            // Error or EOF stops input
            break;
        }
    }

    // Display for testing purposes
    for (temp = list; temp != NULL; temp = temp->next)
    {
        printf("%s\n", temp->data.name);
    }

    // Clean up our dynamic memory
    while (list != NULL)
    {
        struct node *next = list->next;

        free(list->data.name);
        free(list);

        list = next;
    }

    return 0;
}

thanks for you Answere .
could you please explain what does this line exactly do ?

temp->next = list;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.