Удаление контакта из кода телефонной книги в c - PullRequest
0 голосов
/ 17 февраля 2019

Не удается удалить контакт из кода моей телефонной книги.Другие функции работают нормально, но когда я удаляю контакт, он просто останавливает программу.

Я пробовал искать другие примеры, но пока не нашел ничего, что бы сработало для меня.

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

struct contact {                // Data structure that holds contact information 
    char FirstName[10];         // Array for first name
    char LastName[10];          // Array for last name
    int PhoneNum;               // Phone number
};

int main() {

    // Setting up variables
    int Function = 0;
    int Choice = 0;
    char FName[200][10];
    char LName[200][10];
    int PNum = 0;
    int n = 1;
    int size = 1;
    struct contact *con = (struct contact *)malloc(size * sizeof(struct contact));
    int b = 0, a = 0;
    int DelCon = 0;

    do {     // Will loop through the main function until the user decides to exit the program

        // Prints out the main menu of the phone book
        printf("\nPhone Book");
        printf("\n[1] Add a contact");
        printf("\n[2] Delete a contact");
        printf("\n[3] Show contacts");
        printf("\n[4] Exit program");
        printf("\n\nWhat function would you like to use?\n");       // Asks for user input
        scanf("%d", &Choice);

        switch (Choice) {
        case 1:     // Case to add a contact into the phone book
            printf("\nYou chose to add a contact.");
            printf("\nFirst name: ");
            scanf("%s", &FName[b]);
            printf("\nLast name: ");
            scanf("%s", &LName[b]);
            printf("\nPhone number (Numbers only): ");
            scanf("%d", &PNum);
            printf("\nRecord added to the phone book");

            // Records the information given into the structure
            if (n >= size)
            {
                size = size * 2;
                con = (struct contact*)realloc(con, size * sizeof(struct contact));
            }
            a = (n - 1);

            strcpy(con[a].FirstName, FName[b]);
            strcpy(con[a].LastName, LName[b]);
            con[a].PhoneNum = PNum;

            b = (b + 1);
            n++;

            // Prints out the given information
            printf("\n\nNew contact:");
            printf("\nFirst name: %s", con[a].FirstName);
            printf("\nLast name: %s", con[a].LastName);
            printf("\nPhone number: %d", con[a].PhoneNum);
            printf("\nContact number is %d", a);
            printf("\n");
            break;
        case 2:     // Case to delete a contact from the phone book
            printf("\nYou chose to delete a contact.");
            printf("\nWhich contact would you like to delete? Specify by contact number. ");
            scanf("%d", &DelCon);
            a = DelCon;
            char DelF = 0;
            char DelL = 0;
            int DelNum = 0;
            strcpy(con[a].FirstName, DelF);
            strcpy(con[a].LastName, DelL);
            strcpy(con[a].PhoneNum, DelNum);
            printf("\nContact deleted");
            printf("\n");
            break;
        case 3:     // Case to see all of the entered contacts
            printf("\nYou chose to show the contacts.");
            for (a = 0; a < (n - 1); a++) {
                printf("\nContact #%d", a);
                printf("\nFirst name: %s", con[a].FirstName);
                printf("\nLast name: %s", con[a].LastName);
                printf("\nPhone number: %d", con[a].PhoneNum);
                printf("\n");
            }
            break;
        case 4:
            printf("Goodbye!");
            break;
        }
    } while (Choice != 4);
    return 0;
}

Вот что напечатал мой код.

Phone Book
[1] Add a contact
[2] Delete a contact
[3] Show contacts
[4] Exit program

What function would you like to use?
1

You chose to add a contact.
First name: test

Last name: 1

Phone number (Numbers only): 1234567

Record added to the phone book

New contact:
First name: test
Last name: 1
Phone number: 1234567
Contact number is 0

Phone Book
[1] Add a contact
[2] Delete a contact
[3] Show contacts
[4] Exit program

What function would you like to use?
1

You chose to add a contact.
First name: Test

Last name: 2

Phone number (Numbers only): 8901234

Record added to the phone book

New contact:
First name: Test
Last name: 2
Phone number: 8901234
Contact number is 1

Phone Book
[1] Add a contact
[2] Delete a contact
[3] Show contacts
[4] Exit program

What function would you like to use?
3

You chose to show the contacts.
Contact #0
First name: test
Last name: 1
Phone number: 1234567

Contact #1
First name: Test
Last name: 2
Phone number: 8901234

Phone Book
[1] Add a contact
[2] Delete a contact
[3] Show contacts
[4] Exit program

What function would you like to use?
2

You chose to delete a contact.
Which contact would you like to delete? Specify by contact number. 0

--------------------------------
Process exited with return value 3221225477

Это должно быть удаление контакта и возврат в меню.

1 Ответ

0 голосов
/ 17 февраля 2019

Процесс завершен с возвращаемым значением 3221225477

Первое, что нужно сделать при компиляции, это запросить максимальный уровень предупреждения, если я введу gcc -pedantic -Wextra в вашем коде, компилятор выдаст этистроки:

       char DelF = 0;
       char DelL = 0;
       int DelNum = 0;
       strcpy(con[a].FirstName, DelF);
       strcpy(con[a].LastName, DelL);
       strcpy(con[a].PhoneNum, DelNum);

strcpy неверны, поскольку вторым параметром является char / int , а char * (с нулевым символом окончания) ожидается, поведение не определено, в вашем случае сбой.Обратите внимание, что PhoneNum является int , а не массивом char, поэтому для него будет хуже, если я могу сказать.

Если цель состоит в том, чтобы очистить 2 строкии сбросьте номер телефона, просто сделайте:

con[a].FirstName[0] = 0;
con[a].LastName[0] = 0;
con[a].PhoneNum = 0;

После этих исправлений выполняется:

Phone Book
[1] Add a contact
[2] Delete a contact
[3] Show contacts
[4] Exit program

What function would you like to use?
1

You chose to add a contact.
First name: test

Last name: 1

Phone number (Numbers only): 1234567

Record added to the phone book

New contact:
First name: test
Last name: 1
Phone number: 1234567
Contact number is 0

Phone Book
[1] Add a contact
[2] Delete a contact
[3] Show contacts
[4] Exit program

What function would you like to use?
1

You chose to add a contact.
First name: Test

Last name: 2

Phone number (Numbers only): 8901234

Record added to the phone book

New contact:
First name: Test
Last name: 2
Phone number: 8901234
Contact number is 1

Phone Book
[1] Add a contact
[2] Delete a contact
[3] Show contacts
[4] Exit program

What function would you like to use?
3

You chose to show the contacts.
Contact #0
First name: test
Last name: 1
Phone number: 1234567

Contact #1
First name: Test
Last name: 2
Phone number: 8901234

Phone Book
[1] Add a contact
[2] Delete a contact
[3] Show contacts
[4] Exit program

What function would you like to use?
2

You chose to delete a contact.
Which contact would you like to delete? Specify by contact number. 0

Contact deleted

Phone Book
[1] Add a contact
[2] Delete a contact
[3] Show contacts
[4] Exit program

Однако контакт не действительно удален , он все еще присутствуетдаже опустошен в вашем списке, если я выполню команду 3 после удаления, которая выдаст:

You chose to show the contacts.
Contact #0
First name: 
Last name: 
Phone number: 0

Contact #1
First name: Test
Last name: 2
Phone number: 8901234

Вам нужно удалить запись из con .Вам также необходимо проверить правильность ранга удаляемого элемента.

Обратите внимание, что n странно , поскольку оно не содержит количество записейно еще одна, когда книга пуста, она уже имеет значение 1, затем 2 и т. д.

b избыточно с n , поскольку оно имеет значение n-1.Это индекс для FName и LName , но я не вижу интереса к этим двум двумерным массивам, вы можете напрямую scanf в con или просто определите их как простой массив символов.Лучший способ - удалить b и FName и LName .

DelCon также бесполезен, поскольку он простопромежуточное значение для установки a .

Функция никогда не используется.

Когда вы scanf строка ограничивает размерстрока ввода, чтобы не рисковать выходить из получателя.


Модифицированная версия, учитывающая мое предыдущее замечание:

int main() {

    // Setting up variables
    int Choice = 0;
    int n = 0;
    int size = 1;
    struct contact *con = (struct contact *)malloc(size * sizeof(struct contact));
    int a;

    do {     // Will loop through the main function until the user decides to exit the program

        // Prints out the main menu of the phone book
        printf("\nPhone Book");
        printf("\n[1] Add a contact");
        printf("\n[2] Delete a contact");
        printf("\n[3] Show contacts");
        printf("\n[4] Exit program");
        printf("\n\nWhat function would you like to use?\n");       // Asks for user input
        scanf("%d", &Choice);

        switch (Choice) {
        case 1:     // Case to add a contact into the phone book
            if (n == size)
            {
                size = size * 2;
                con = (struct contact*)realloc(con, size * sizeof(struct contact));
            }
            // Records the information given into the structure
            printf("\nYou chose to add a contact.");
            printf("\nFirst name: ");
            scanf("%9s", con[n].FirstName);
            printf("\nLast name: ");
            scanf("%9s", con[n].LastName);
            printf("\nPhone number (Numbers only): ");
            scanf("%d", &con[n].PhoneNum);
            printf("\nRecord added to the phone book");

            // Prints out the given information
            printf("\n\nNew contact:");
            printf("\nFirst name: %s", con[n].FirstName);
            printf("\nLast name: %s", con[n].LastName);
            printf("\nPhone number: %d", con[n].PhoneNum);
            printf("\nContact number is %d", n);
            printf("\n");
            n += 1;
            break;
        case 2:     // Case to delete a contact from the phone book
            printf("\nYou chose to delete a contact.");
            printf("\nWhich contact would you like to delete? Specify by contact number. ");
            scanf("%d", &a);
            if ((a < 0) || (a >= n))
              printf("\ninvalid rank of contact");
            else {
              /* if you do not have bcopy use memmove */
              bcopy(&con[a+1], &con[a], (n - 1 - a) * sizeof(struct contact));
              n -= 1;
              printf("\nContact deleted");
            }
            printf("\n");
            break;
        case 3:     // Case to see all of the entered contacts
            printf("\nYou chose to show the contacts.");
            for (a = 0; a < n; a++) {
                printf("\nContact #%d", a);
                printf("\nFirst name: %s", con[a].FirstName);
                printf("\nLast name: %s", con[a].LastName);
                printf("\nPhone number: %d", con[a].PhoneNum);
                printf("\n");
            }
            break;
        case 4:
            puts("\nGoodbye!");
            break;
        default:
            puts("\ninvalid choice");
        }
    } while (Choice != 4);
    return 0;
}

Компиляция и выполнение:

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra b.c
pi@raspberrypi:/tmp $ ./a.out

Phone Book
[1] Add a contact
[2] Delete a contact
[3] Show contacts
[4] Exit program

What function would you like to use?
1

You chose to add a contact.
First name: test

Last name: 1

Phone number (Numbers only): 1234567

Record added to the phone book

New contact:
First name: test
Last name: 1
Phone number: 1234567
Contact number is 0

Phone Book
[1] Add a contact
[2] Delete a contact
[3] Show contacts
[4] Exit program

What function would you like to use?
1

You chose to add a contact.
First name: Test

Last name: 2

Phone number (Numbers only): 8901234

Record added to the phone book

New contact:
First name: Test
Last name: 2
Phone number: 8901234
Contact number is 1

Phone Book
[1] Add a contact
[2] Delete a contact
[3] Show contacts
[4] Exit program

What function would you like to use?
3

You chose to show the contacts.
Contact #0
First name: test
Last name: 1
Phone number: 1234567

Contact #1
First name: Test
Last name: 2
Phone number: 8901234

Phone Book
[1] Add a contact
[2] Delete a contact
[3] Show contacts
[4] Exit program

What function would you like to use?
2

You chose to delete a contact.
Which contact would you like to delete? Specify by contact number. 2

invalid rank of contact

Phone Book
[1] Add a contact
[2] Delete a contact
[3] Show contacts
[4] Exit program

What function would you like to use?
2

You chose to delete a contact.
Which contact would you like to delete? Specify by contact number. 0

Contact deleted

Phone Book
[1] Add a contact
[2] Delete a contact
[3] Show contacts
[4] Exit program

What function would you like to use?
3

You chose to show the contacts.
Contact #0
First name: Test
Last name: 2
Phone number: 8901234

Phone Book
[1] Add a contact
[2] Delete a contact
[3] Show contacts
[4] Exit program

What function would you like to use?
4

Goodbye!
pi@raspberrypi:/tmp $ 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...