Language/자료구조

[4] C review < 전화번호부 알고리즘 version1.0 >

Return 2021. 11. 22. 10:02

동작 방식 : 명령어 입력받고 각 기능에 해당되는 값들을 추가로 받는다. 

 

생각해야 될점 2가지!

 

1. names와 numbers배열을 어떻게 처리할 것인가 ? 

위와 같이 names와 numbers배열은 각각의 칸에 이름과 전화번호가 남긴 배열이 들어가야 한다. 즉, names numbers의 배열의 타입이 일반적인 char형이 아니라 cahr* 형이 되어야한다. 

 

 

2. names와 numbers배열에 키보드에서 입력받은 이름과 전화번호를 넣을때 strdup를 쓰는 이유 ?

buffer 배열들은 함수내에서 선언된 것들이기 때문에 함수가 종료 된후 모두 사라진다. 즉, 키보드로 입력받은 이름과 전화번호들이 소멸되기 때문에 제대로 저장할 수 없다. 이는 strdup함수를 쓰면서 해결할 수 있는데 이는 buffer배열의 값을 소멸되지 않는 배열로 복제한 후 names와 numbers 배열에 저장한다. 

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define CAPACITY 100
#define BUFFER_SIZE 20

// Phone version 1.0
// 1. 프롬프트에 명령 입력받는다.
// 2. 입력후 각 명령에 필요한 인자를 입력받는다.
// 3. add,find,status,delete,exit

char *names[CAPACITY];
char *numbers[CAPACITY];
int n = 0;

void add();
void find();
void status();
void delete ();

int main()
{

    char command[BUFFER_SIZE];

    while (1)
    {
        printf("$ ");
        scanf("%s", command);

        if (strcmp(command, "add") == 0)
        {
            add();
        }
        else if (strcmp(command, "find") == 0)
        {
            find();
        }
        else if (strcmp(command, "status") == 0)
        {
            status();
        }
        else if (strcmp(command, "delete") == 0)
        {
            delete ();
        }
        else if (strcmp(command, "exit") == 0)
            break;
    }

    return 0;
}

void add()
{

    char buf1[BUFFER_SIZE], buf2[BUFFER_SIZE];
    scanf("%s", buf1);
    scanf("%s", buf2);

    names[n] = strdup(buf1);
    numbers[n] = strdup(buf2);
    n++;

    printf("%s was added succesfully", buf1);
}

void find()
{
    char buf[BUFFER_SIZE];
    scanf("%s", buf);

    for (int i = 0; i < n; i++)
    {
        if (strcmp(buf, names[i]) == 0)
        {
            printf("%s", numbers[i]);
        }
    }
}

void status()
{
    int i;
    for (i = 0; i < n; i++)
    {
        printf("%s %s\n", names[i], numbers[i]);
    }
    printf("Total %d persons.\n", n);
}

void delete ()
{
    char buf[BUFFER_SIZE];
    scanf("%s", buf);
    int i;

    for (i = 0; i < n; i++)
    {
        if (strcmp(buf, names[i]) == 0)
        {
            names[i] = names[n - 1];
            numbers[i] = numbers[n - 1];
            n--;
            printf("%s was deleted sucessfully.\n", buf);
            return;
        }
    }
    printf("No person named %s", buf);
}