(C언어_강의) Structure Array 연습문제

goodjam92·2021년 8월 6일
0

C언어_공부

목록 보기
2/2

// 프로그램 작성 (도서 입력 프로그램)
// 1. 도서 제목 입력
// 2. 저자 입력
// 3. 가격 입력
// x. 도서 제목 입력에 그냥 Enter를 치면 종료가 됨
// 간단한 프로그램이라 정상적인 입력을 하는 것으로 간주
// 도서 제목 입력 받은 첫 글자가 \n 일 경우 \0 (NULL)로 변환하여
// 프로그램이 종료가 되도록 함.

#include <stdio.h>	
#include <string.h>
#define MAX_TITLE 40
#define MAX_AUTHOR 40
#define MAX_BOOKS 3

char* s_gets(char* st, int n)	// 입력받은 글자가 '\n' 일 경우를 판단하는 함수
{
	char* ret_val;
	char* find;

	ret_val = fgets(st, n, stdin);

	if (ret_val)
	{
		find = strchr(st, '\n');	//  Newline을 찾는 기능
		if (find)				
			*find = '\0';		// \n을 찾으면 \0로 바꾸어서 문자열의 기능을 하게 함.
		else
			while (getchar() != '\n')
				continue;	// 버퍼를 없앰
	}

	return ret_val;
}

struct book
{
	char title[MAX_TITLE];
	char author[MAX_AUTHOR];
	float price;
};


int main()
{
	struct book library[MAX_BOOKS] = { {"empty", "empty", 0.0f} };
	
	int count = 0;

	while (1)
	{
		printf("Input a book title or press [Enter] to stop.\n>>");

		if (s_gets(library[count].title, MAX_TITLE) == NULL) break;
		if (library[count].title[0] == '\0') break;
        
	// 이 부분에서 나는 아래와 같이 입력하였음. NULL 캐릭터를 판단하는 if를 따로 작성해주어야 하는 듯
        // s_gets(library[count].title, MAX_TITLE) == NULL && library[count].title == '\0') break;

		printf("Input the author\n>>");
		fgets(library[count].author, MAX_AUTHOR, stdin);

		printf("Input the price.\n>>");
		scanf("%f", &library[count].price);
		getchar();

		count++;

		if (count == MAX_BOOKS)
		{
			printf("No more books.\n");
			break;
		}
	}


	if (count == 0)
		printf("No books to show.\n");
	else
	{
		printf("The list of books : \n");
		for (int j = 0; j < count; j++)
			printf("\"%s\" written by %s : $%.1f\n", 
				library[j].title, library[j].author, library[j].price);
	}


	return 0;
profile
습관을 들이도록 노력하자!

0개의 댓글