• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

14-4 구조체 배열 연습 문제중

20.09.05 21:53 작성 조회수 170

0

구조체 연습 문제중 s_gets  함수를 통해서 책 이름을 적는 코드중에

저는 if문을 사용하지 않고

s_gets(library[count].title, MAX_AUTHOR) ;

로 문장을 끝내었는데,

강의에서는

if (s_gets(library[count].title, MAX_AUTHOR) == NULL) break;

이렇게 작성을 해주셨습니다.

분명히 전 강의해서 설명 해주셨던거 같아서 계속 찾아보다가 찾을 수 없어서 이렇게 질문을 드립니다.

왜 저렇게 작성을 하셨는지 알려주실수 있으신가요?

답변해주시면 감사드리겠습니다. ( 밑에는 강의 예제 코드를 올려드리겠습니다.)

#define _CRT_SECURE_NO_WARNINGS

#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)

{

char* ret_val;

char* find;

ret_val = fgets(st, n, stdin); // scanf 불가

// 빈칸이 있는 문자열 입력 받을 수 있다.

if (ret_val)

{

find = strchr(st, '\n');

if (find)

*find = '\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_AUTHOR) == NULL) break; 이 부분이 궁금한데 답변해주시면 감사드리겠습니다.

s_gets(library[count].title, MAX_AUTHOR); 

if (library[count].title[0] == '\0') break;

printf("Input the author . \n>>");

s_gets(library[count].author, MAX_AUTHOR);

printf("Input the price . \n>>");

int flag = scanf("%f", &library[count].price);

while (getchar() !='\n')

continue;

count++;

if (count == MAX_BOOKS)

{

printf("No more books . \n");

break;

}

}

if (count > 0)

{

printf("\nThe list of books :\n");

for (int index = 0; index < count; index++)

printf("\%s\" wiritten by %s: $%.1f\n",

library[index].title, library[index].author, library[index].price);

}

else

printf("No books to show. \n");

return 0;

}

답변 2

·

답변을 작성해보세요.

1

신성균님의 프로필

신성균

질문자

2020.09.06

아! ㅋㅋ 무슨 말씀인지 알아들었습니다.

답변해주셔서 감사합니다.

1

Hello Yeo님의 프로필

Hello Yeo

2020.09.05

안녕하세요?
프로그램 실행 후 EOF를 입력으로 넣어보시는 것이 생각하시는데 도움이 될 것 같네요.
아마 성균님도 이런 프로그램의 실행을 원치 않으실 거라 생각합니다.