공부 흔적남기기

c 언어 전화번호부 .version.1.0 본문

프로그래밍 언어/c study

c 언어 전화번호부 .version.1.0

65살까지 코딩 2021. 2. 19. 20:37
728x90
반응형
#include <stdio.h>
#include <string.h>
#define CAPACITY 100
#define BUFFER_SIZE 20

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

void add();
void find();
void status();
void remove();


int main()
{
	char command[BUFFER_SIZE] = { 0, };
	
	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)
			remove();
		else if (strcmp(command, "exit") == 0)
			break;
		else
		{
			printf("fail");
			printf("\n");
			continue;
		}
	}

	return 0;
}
void add()
{
	char buf1[BUFFER_SIZE] = { 0, };
	char buf2[BUFFER_SIZE] = { 0, };
	scanf("%s", buf1); //strcpy를 쓰게되면 buf1가 name으로 들어가게되는데 함수가끝날때 buf가 사라지므로 의미가 없어짐
	scanf("%s", buf2); // 따라서 strdup를 통해 새로운 배열을 동적할당해서 넣어줘야함

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

	printf("%s was added successfully. \n", buf1);
}

void find()
{
	char buf[BUFFER_SIZE] = { 0, };
	scanf("%s", buf);
	for (int i = 0; i < n; i++)
	{
		if (strcmp(buf, names[i]) == 0);
		{
			printf("%s \n", numbers[i]);
			return;
		}
	}
	printf("No person named '%s' exists. \n", buf);
	return;
}

void remove()
{
	char buf[BUFFER_SIZE];
	scanf("%s", buf);
	for (int i = 0; i < n; i++)
	{
		if (strcmp(buf, names[i]) == 0)
		{
			names[i] = names[n - 1];
			numbers[i] = numbers[n - 1];
			n--;
			printf("'%s' is deleted successfully \n", buf);
			return;
		}
	}
	printf("No person named '%s' exists. \n", buf);
	return;
}

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

//c로 배우는 자료구조 및 여러가지 예제 실습 by권오흠교수님 in 인프런

728x90
반응형