Computer >> 컴퓨터 >  >> 프로그래밍 >> C 프로그래밍

C 언어 switch-case 문으로 구현하는 도서관 관리 시스템 프로그램

문제 개요

C 프로그래밍을 이용하면 별도의 데이터베이스 없이도 도서관의 도서 정보를 효율적으로 저장하고 관리할 수 있습니다. 이번 글에서는 구조체(struct)switch-case 문을 활용해 도서 추가, 도서 목록 조회, 보유 도서 수 확인 기능을 갖춘 간단한 도서관 관리 시스템을 만드는 방법을 단계별로 살펴보겠습니다.

알고리즘

프로그램의 전체적인 동작 흐름은 다음과 같습니다.

1단계: 도서 데이터를 담을 구조체를 선언한다
2단계: 반복문에 사용할 변수를 선언한다
3단계: switch-case 문으로 각 기능(모듈)을 분기 처리한다
4단계:
    case 1 → 도서 정보 추가
    case 2 → 도서 정보 출력
    case 3 → 도서관 내 보유 도서 수 확인
    case 4 → 프로그램 종료

전체 소스 코드

아래 예제 코드는 최대 100권의 도서 정보를 배열에 저장하며, 사용자가 메뉴 번호를 입력할 때마다 해당 기능을 수행합니다.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
struct library{
   char bookname[50];
   char author[50];
   int noofpages;
   float price;
};
int main(){
   struct library lib[100];
   char bookname[30];
   int i,j, keepcount;
   i=j=keepcount = 0;
   while(j!=6){
      printf("
1. Add book information
");
      printf("2.Display book information
");
      printf("3. no of books in the library
");
      printf("4. Exit");
      printf ("

Enter one of the above : ");
      scanf("%d",&j);
      switch (j){
         /* 도서 추가 */
         case 1:
            printf ("Enter book name = ");
            scanf ("%s",lib[i].bookname);
            printf ("Enter author name = ");
            scanf ("%s",lib[i].author);
            printf ("Enter pages = ");
            scanf ("%d",&lib[i].noofpages);
            printf ("Enter price = ");
            scanf ("%f",&lib[i].price);
            keepcount++;
            i++;
            break;
         case 2:
            printf("you have entered the following information
");
            for(i=0; i<keepcount; i++){
               printf ("book name = %s
",lib[i].bookname);
               printf ("	 author name = %s
",lib[i].author);
               printf ("	 pages = %d
",lib[i].noofpages);
               printf ("	 price = %f
",lib[i].price);
            }
            break;
         case 3:
            printf("
 No of books in library : %d", keepcount);
            break;
         case 4:
            exit (0);
      }
   }
   return 0;
}

코드 핵심 설명

1. 구조체(struct library)로 도서 정보 모델링

하나의 책은 bookname(책 이름), author(저자), noofpages(페이지 수), price(가격)이라는 서로 다른 자료형의 데이터를 가집니다. C 언어에서는 이처럼 관련된 데이터를 하나로 묶을 때 구조체를 사용합니다.

2. while 루프와 switch-case의 조합

while(j!=6) 조건에 따라 프로그램은 사용자가 종료 메뉴를 선택하기 전까지 계속 반복 실행됩니다. 각 반복마다 switch(j)가 입력된 메뉴 번호를 판별해 알맞은 기능을 수행합니다. 이러한 메뉴 기반 구조는 콘솔 응용프로그램에서 가장 널리 쓰이는 설계 방식입니다.

3. keepcount 변수의 역할

도서가 추가될 때마다 keepcount가 1씩 증가하여 현재까지 등록된 도서의 총 권수를 추적합니다. 이 값은 도서 목록 전체를 출력할 때 반복 범위를 정하는 데에도 활용됩니다.

실행 결과

1. Add book information
2.Display book information
3. no of books in the library
4. Exit

Enter one of the above : 1
Enter book name = HarryPotter
Enter author name = hp
Enter pages = 250
Enter price = 350.6

1. Add book information
2.Display book information
3. no of books in the library
4. Exit

Enter one of the above : 2
you have entered the following information
book name = HarryPotter
         author name = hp
         pages = 250
         price = 350.600006

1. Add book information
2.Display book information
3. no of books in the library
4. Exit

Enter one of the above : 3

No of books in library : 1
1. Add book information
2.Display book information
3. no of books in the library
4. Exit

Enter one of the above : 4

참고 사항

  • float 자료형의 특성상 가격이 350.600006처럼 미세한 오차와 함께 출력될 수 있으며, 이는 부동소수점 연산의 일반적인 현상입니다. 원하는 형식으로 출력하려면 %.2f 같은 서식 지정자를 사용하면 됩니다.
  • 현재 코드는 종료 조건이 j != 6인데 실제 종료 메뉴는 4번이므로, while(j != 4) 또는 무한 루프 + exit() 구조로 다듬으면 더 명확해집니다.
  • 공백을 포함한 책 이름을 입력받으려면 %s 대신 scanf("%[^\n]", ...)gets(), fgets() 계열 함수를 사용하는 것이 좋습니다.

이처럼 구조체와 switch-case 문만으로도 실용적인 콘솔 기반 도서관 관리 시스템을 손쉽게 구현할 수 있습니다. 여기에 검색, 삭제, 파일 입출력 기능을 추가하면 더욱 완성도 높은 프로그램으로 발전시킬 수 있습니다.