티스토리 뷰

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


#define CAPACITY 100
#define BUFFER_SIZE 20


char * names[CAPACITY];          // names
char * numbers[CAPACITY];        // phone numbers
int n = 0;                         // number of people in phone directory


void add()
{

 char buf1[BUFFER_SIZE], buf2[BUFFER_SIZE];        //지역변수들
 scanf_s("%s", buf1,sizeof(buf1));
 scanf_s("%s", buf2, sizeof(buf2));

 names[n] = strdup(buf1);           //strdup strcpy 차이?
 numbers[n] = strdup(buf2);
 n++;

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

}

void find()
{
 char buf[BUFFER_SIZE];        //지역변수들
 scanf_s("%s", buf, sizeof(buf));

 int i = 0;
 for (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);
}


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


void del()
{
 char buf[BUFFER_SIZE];
 scanf_s("%s", buf,sizeof(buf));

 int i = 0;
 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 successfully. \n", buf);
   return;
  }
 }
 printf("No person named '%s' exists.\n", buf);
}


int main(void)
{

 char command[BUFFER_SIZE];

 while (1)
 {
  printf("$ ");
  scanf_s("%s", command,sizeof(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)
   del();
  else if (strcmp(command, "exit") == 0)
   break;
 }

 return 0;
}


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함