본문 바로가기
휴지통/C 프로그래밍

도전 프로그래밍 4-1, 4-2

by 신재권 2021. 1. 29.
//4-1
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>

typedef struct book
{
	char title[30];			//제목
	char author[10];		//저자
	int npage;				//페이지 수
}Book;


int main() {
	Book books[3];
	int i;
	
	printf("도서 정보 입력 \n");
	for (i = 0; i < 3; i++)
	{
		printf("저자 :");			fgets(books[i].author, 3, stdin); 
		books[i].author[strlen(books[i].author) - 1] = 0;   //엔터키제거
		printf("제목 :");			fgets(books[i].title, 3, stdin);
		books[i].title[strlen(books[i].title) - 1] = 0;   //엔터키제거
		printf("페이지 수 :");	scanf("%d", &books[i].npage); getchar();
	}

	putchar('\n');
	printf("도서 정보 출력 \n");
	for (i = 0; i < 3; i++)
	{
		printf("저자 : %s\n", books[i].author);
		printf("제목 : %s\n", books[i].title);
		printf("페이지 수 : %d\n", books[i].npage);
	}


	return 0;
}

4-1은 [제목, 저자명, 페이지]수에 대한 정보를 저장할수 있는 구조체를 정의 후, 구조체 배열로 정보를 저장하고 출력하는 문제이고

printf("저자 :"); fgets(books[i].author, 3, stdin);

books[i].author[strlen(books[i].author) - 1] = 0; //엔터키제거

이 문장을 삽입해줌으로 배열안에 저장된 데이터가 1줄어든다

scanf함수 선언후 getchar(); 를 선언해 입력버퍼를 비워준다.

 

// 4-2
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct book
{
	char title[30];			//제목
	char author[10];		//저자
	int npage;				//페이지 수
}Book;


int main() {
	int n;
	Book* books;

	printf("저장할 책의 갯수 : ");		scanf("%d", &n);		getchar();
	books = (Book*)malloc(sizeof(Book) * n);

	for (int i = 0; i < n; i++) {
		printf("제목 :");
		fgets(books[i].title, sizeof(books[i].title), stdin);
		books[i].title[strlen(books[i].title) - 1] = 0;
		printf("저자 :");
		fgets(books[i].author, sizeof(books[i].author), stdin);
		books[i].author[strlen(books[i].author) - 1] = 0;
		printf("페이지 수 :");
		scanf("%d", &books[i].npage);		getchar();
	}
	for (int i = 0; i < n; i++) {
		printf("제목 : %s\n", books[i].title);
		printf("저자 : %s\n", books[i]. author);
		printf("제목 : %d\n", books[i].npage);

	}


	return 0;
}

 

4-2는 4-1과 예제는 같지만 구조체 배열대신 구조체 포인터 배열을 선언하고, 입력받을 책의 갯수를 동적으로 할당하는 형태이다.

4-1하고 다른건 별로 없고 처음 정의만 다르다.